สำหรับสิ่งนี้ ให้ใช้ aggregate() ร่วมกับ $unwind ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo583.insert([ ... { ... "details1" : [ ... { ... "details2" : [ ... { ... "isMarried" : true, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Bob" ... } ... ] ... }, ... { ... "details2" : [ ... { ... "isMarried" : false, ... "Name" : "Chris" ... }, ... { ... "isMarried" : true, ... "Name" : "Mike" ... } ... ] ... } ... ] ... } ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 1, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo583.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [ { "details2" : [ { "isMarried" : true, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Bob" } ] }, { "details2" : [ { "isMarried" : false, "Name" : "Chris" }, { "isMarried" : true, "Name" : "Mike" } ] } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อกรองเอกสารย่อยตามเอกสารย่อย -
> var q= [ ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... }, ... { ... "$unwind": "$details1" ... }, ... { ... "$unwind": "$details1.details2" ... }, ... { ... "$match": { ... "details1.details2.isMarried": true, ... "details1.details2.Name": "Chris" ... } ... } ... ]; > db.demo583.aggregate(q).pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : { "details2" : { "isMarried" : true, "Name" : "Chris" } } }