เพื่อค้นหาเอกสารที่อาร์เรย์มีแอตทริบิวต์เฉพาะ ให้ใช้ $and ร่วมกับ Dot Notiation (.)
สร้างคอลเลกชันพร้อมเอกสารที่มีอาร์เรย์ StudentInformation (แต่ละรายการมี StudentName และ StudentAge):
> db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08b56e25ddae1f53b62219") }
> db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e08b58625ddae1f53b6221a") }
แสดงเอกสารทั้งหมด:
> db.demo2.find().pretty();
ผลลัพธ์ - 2 เอกสาร แต่ละอันมีอาร์เรย์ StudentInformation 2 รายการ:
คำสั่งค้นหาเอกสารที่อาร์เรย์ StudentInformation มีทั้ง "Carol" และ "Bob" (ใช้ $and กับ Dot Notation StudentInformation.StudentName):
> db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});ผลลัพธ์ - ได้เฉพาะเอกสารที่ 2 ที่มีทั้ง Carol และ Bob ในอาร์เรย์เดียวกัน: