ในการตรวจสอบการมีอยู่ของหลายฟิลด์ ให้ใช้ $exists ร่วมกับ $and ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo475.insertOne({"StudentFirstName":"Chris","StudentAge":23});{
"acknowledged" : true,
"insertedId" : ObjectId("5e80c113b0f3fa88e2279088")
}
>
db.demo475.insertOne({"StudentFirstName":"Bob","StudentAge":21,"StudentCountryName":"US"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e80c127b0f3fa88e2279089")
}
> db.demo475.insertOne({"StudentFirstName":"David","StudentAge":22});{
"acknowledged" : true,
"insertedId" : ObjectId("5e80c135b0f3fa88e227908a")
} แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo475.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e80c113b0f3fa88e2279088"), "StudentFirstName" : "Chris", "StudentAge" :
23 }
{ "_id" : ObjectId("5e80c127b0f3fa88e2279089"), "StudentFirstName" : "Bob", "StudentAge" :
21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e80c135b0f3fa88e227908a"), "StudentFirstName" : "David", "StudentAge"
: 22 } ต่อไปนี้เป็นแบบสอบถามเพื่อตรวจสอบการมีอยู่ของหลายฟิลด์ -
> db.demo475.find(
... { '$and':
... [ { 'StudentFirstName': { '$exists': true } },
... { 'StudentAge': { '$exists': true } },
... { 'StudentCountryName': { '$exists': true } } ]
... }
... ); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e80c127b0f3fa88e2279089"), "StudentFirstName" : "Bob", "StudentAge" :
21, "StudentCountryName" : "US" }