Sử dụng toán tử $or để tìm tài liệu khớp với ít nhất một trong các điều kiện trên các trường khác nhau.
Tạo collection:
> db.demo371.insertOne({"Name":"David","CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e57f6982ae06a1609a00af2") }
> db.demo371.insertOne({"Name":"John","CountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e57f69e2ae06a1609a00af3") }
> db.demo371.insertOne({"Name":"Bob","CountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e57f6a42ae06a1609a00af4") }
> db.demo371.insertOne({"Name":"Mike","CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e57f6ba2ae06a1609a00af5") }
Xem dữ liệu:
> db.demo371.find();
{ "_id" : ObjectId("5e57f6982ae06a1609a00af2"), "Name" : "David", "CountryName" : "US" }
{ "_id" : ObjectId("5e57f69e2ae06a1609a00af3"), "Name" : "John", "CountryName" : "UK" }
{ "_id" : ObjectId("5e57f6a42ae06a1609a00af4"), "Name" : "Bob", "CountryName" : "AUS" }
{ "_id" : ObjectId("5e57f6ba2ae06a1609a00af5"), "Name" : "Mike", "CountryName" : "US" }
Tìm tài liệu có Name="David" HOẶC CountryName="UK":
> db.demo371.find({ $or: [ { Name: "David" }, { CountryName: "UK" } ] })
Kết quả (David US và John UK):
{ "_id" : ObjectId("5e57f6982ae06a1609a00af2"), "Name" : "David", "CountryName" : "US" }
{ "_id" : ObjectId("5e57f69e2ae06a1609a00af3"), "Name" : "John", "CountryName" : "UK" }
Các toán tử logic:
$or: ít nhất một điều kiện đúng$and: tất cả điều kiện đúng (mặc định nếu không viết)$nor: không điều kiện nào đúng$not: phủ định một điều kiện