ใช้ $or ใน find() เพื่อค้นหาเอกสารที่ตรงกับเงื่อนไขใดเงื่อนไขหนึ่งจากหลายฟิลด์
ตัวอย่างข้อมูลทดสอบ
> db.demo371.insertOne({"Name":"David","CountryName":"US"});
> db.demo371.insertOne({"Name":"John","CountryName":"UK"});
> db.demo371.insertOne({"Name":"Bob","CountryName":"AUS"});
> db.demo371.insertOne({"Name":"Mike","CountryName":"US"});
แสดงข้อมูลทั้งหมด
> 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"
}
คิวรี่ค้นหา Name = "David" OR CountryName = "UK"
> db.demo371.find({ $or: [ { Name: "David" }, { CountryName: "UK" } ] })
ผลลัพธ์
{
"_id" : ObjectId("5e57f6982ae06a1609a00af2"),
"Name" : "David", "CountryName" : "US"
}
{
"_id" : ObjectId("5e57f69e2ae06a1609a00af3"),
"Name" : "John", "CountryName" : "UK"
}
ขยายได้: ใช้ $and สำหรับเงื่อนไข AND, รวม $or/$and ได้หลายระดับ