ใช้ $exists ร่วมกับ dot notation เพื่อตรวจสอบว่าฟิลด์ย่อยในอาร์เรย์มีอยู่หรือไม่ ซึ่งสามารถใช้เป็นเงื่อนไข true/false ได้
ตัวอย่างข้อมูลทดสอบ
> db.demo367.insertOne({
"Id" : "102",
"details" : [
{"Name" : "David"},
{"Age" : 23, "CountryName" : "UK"}
],
"isMarried" : false
});
> db.demo367.insertOne({
"Id" : "101",
"details" : [
{"Name" : "Chris", "Subject" : ["MySQL"]},
{"Age" : 21, "CountryName" : "US"}
],
"isMarried" : true
});
แสดงข้อมูลทั้งหมด
> db.demo367.find();
{
"_id" : ObjectId("5e57e0b62ae06a1609a00ae8"),
"Id" : "102",
"details" : [
{"Name" : "David"},
{"Age" : 23, "CountryName" : "UK"}
],
"isMarried" : false
}
{
"_id" : ObjectId("5e57e0be2ae06a1609a00ae9"),
"Id" : "101",
"details" : [
{"Name" : "Chris", "Subject" : ["MySQL"]},
{"Age" : 21, "CountryName" : "US"}
],
"isMarried" : true
}
คิวรี่ค้นหาเอกสารที่ details ไม่มีฟิลด์ Subject
> db.demo367.find({"details.Subject": {$exists: false}});
ผลลัพธ์
{
"_id" : ObjectId("5e57e0b62ae06a1609a00ae8"),
"Id" : "102",
"details" : [
{"Name" : "David"},
{"Age" : 23, "CountryName" : "UK"}
],
"isMarried" : false
}
คำอธิบาย: $exists: false จะคืนเอกสารที่ในอาร์เรย์ details ไม่มีออบเจ็กต์ใดที่มีฟิลด์ Subject ในตัวอย่าง เอกสาร Id 102 ไม่มี Subject ใน details ทั้งสองออบเจ็กต์ จึงถูกคืนค่า