Toán tử $or thực hiện phép OR logic trên mảng 2+ biểu thức, chọn tài liệu thỏa **ÍT NHẤT MỘT** điều kiện. Tạo collection:
> db.demo674.insertOne({Name:"Chris",Age:21});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f33604263e90dac943eb") }
> db.demo674.insertOne({Name:"David",Age:23});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f33c04263e90dac943ec") }
> db.demo674.insertOne({Name:"Bob",Age:21});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f34204263e90dac943ed") }
> db.demo674.insertOne({Name:"John",Age:24});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3f34804263e90dac943ee") }
Hiển thị dữ liệu:
> db.demo674.find();
Kết quả:
Tìm tài liệu có Name="David" **HOẶC** Age=21:
> db.demo674.find({$or:[{Name:"David"},{Age:21}]});Kết quả 3 tài liệu (David 23 tuổi, Chris 21 tuổi, Bob 21 tuổi):
Lưu ý:
$orđánh giá từng clause riêng biệt, tài liệu khớp bất kỳ clause nào được chọn- Mỗi clause trong $or có thể dùng index khác nhau (index intersection)
- Tạo index trên các trường trong $or để tối ưu:
createIndex({Name:1}), createIndex({Age:1})
Kết hợp $and + $or: {$and: [{Status: "active"}, {$or: [{Type: "A"}, {Type: "B"}]}]} = Status=active VÀ (Type=A HOẶC Type=B).