ในการกรองเอกสารย่อยหลายรายการใน MongoDB ให้ใช้ aggregate() ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo200.insertOne( ... { ... "Id":"101", ... "details1":[ ... { ... "isActive":true, ... "SubjectName":"MySQL" ... },{ ... "isActive":false, ... "SubjectName":"Java" ... } ... ], ... "details2":[ ... { ... "isActive":false, ... "Name":"David" ... },{ ... "isActive":true, ... "Name":"Mike" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3c374f03d395bdc21346e4") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo200.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e3c374f03d395bdc21346e4"), "Id" : "101", "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" }, { "isActive" : false, "SubjectName" : "Java" } ], "details2" : [ { "isActive" : false, "Name" : "David" }, { "isActive" : true, "Name" : "Mike" } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อกรองเอกสารย่อยหลาย -
> var out= [ ... { ... "$match": { ... "Id": "101", ... "details1.isActive": true, ... "details2.isActive": true ... } ... }, ... { "$unwind": "$details1" }, ... { "$unwind": "$details2" }, ... { ... "$match": { ... "details1.isActive": true, ... "details2.isActive": true ... } ... }, ... { ... "$group": { ... "_id": { ... "_id": "$_id", ... "Id": "$Id" ... }, ... "details2": { "$addToSet" : "$details2" }, ... "details1": { "$addToSet" : "$details1" } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "Id": "$_id.Id", ... "details2": 1, ... "details1": 1 ... } ... } ...] > > db.demo200.aggregate(out)
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "details2" : [ { "isActive" : true, "Name" : "Mike" } ], "details1" : [ { "isActive" : true, "SubjectName" : "MySQL" } ], "Id" : "101" }