Khi cần tìm tài liệu thỏa mãn ít nhất một trong nhiều điều kiện trên các trường khác nhau, MongoDB cung cấp toán tử $or kết hợp với find(). Điều này cho phép xây dựng các truy vấn phức tạp với logic "HOẶC".
Tạo dữ liệu mẫu
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"Robert","IsMarried":false});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd4fd1e2cba06f46efe9ef1") }
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"Chris","IsMarried":true});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd4fd322cba06f46efe9ef2") }
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"David","IsMarried":true});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd4fd3b2cba06f46efe9ef3") }
> db.findDocumentWithFilterDemo.insertOne({"ClientName":"Carol","IsMarried":true});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd4fd452cba06f46efe9ef4") }
Xem tất cả tài liệu
> db.findDocumentWithFilterDemo.find().pretty();
{ "_id" : ObjectId("5cd4fd1e2cba06f46efe9ef1"), "ClientName" : "Robert", "IsMarried" : false }
{ "_id" : ObjectId("5cd4fd322cba06f46efe9ef2"), "ClientName" : "Chris", "IsMarried" : true }
{ "_id" : ObjectId("5cd4fd3b2cba06f46efe9ef3"), "ClientName" : "David", "IsMarried" : true }
{ "_id" : ObjectId("5cd4fd452cba06f46efe9ef4"), "ClientName" : "Carol", "IsMarried" : true }
Truy vấn với $or trên nhiều trường
Tìm tài liệu mà ClientName KHÔNG phải "Robert" HOẶC IsMarried KHÔNG phải false:
> db.findDocumentWithFilterDemo.find({
$or: [
{ "ClientName": { $ne: "Robert" } },
{ "IsMarried": { $ne: false } }
]
});
Kết quả
Giải thích
$or: Trả về tài liệu thỏa mãn ít nhất một điều kiện trong mảng$ne: Toán tử "không bằng" (not equal)- Tài liệu của Robert bị loại vì: ClientName = "Robert" (sai điều kiện 1) VÀ IsMarried = false (sai điều kiện 2)
- 3 tài liệu còn lại thỏa mãn ít nhất một điều kiện
Mở rộng
Có thể kết hợp $or với $and, $nor, $not để xây dựng logic truy vấn phức tạp tùy theo nhu cầu nghiệp vụ.