ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.demo118.insertOne( ... { ... "Id" : "101", ... "Name" : "Chris", ... "Subjects" : [ ... "MySQL", ... "MongoDB", ... "Java" ... ], ... "Details" : [ ... { ... "Name" : "David", ... S:"MongoDB" ... }, ... { ... "Name" : "Bob", ... S:"Python" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f0c0cd8f64a552dae6364") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo118.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"), "Id" : "101", "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java" ], "Details" : [ { "Name" : "David", "S" : "MongoDB" }, { "Name" : "Bob", "S" : "Python" } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อใช้ไปป์ไลน์ $addFields -
> db.demo118.aggregate([ ... { ... "$addFields": { ... "Details": { ... "$filter": { ... "input": "$Details", ... "as": "out", ... "cond": { "$in": ["$$out.S", "$Subjects"] } ... } ... } ... } ... } ... ]).pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"), "Id" : "101", "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java" ], "Details" : [ { "Name" : "David", "S" : "MongoDB" } ] }