ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.demo389.insertOne( ... { ... "details":[ ... { ... "Name":[ ... "Chris", ... "David" ... ] ... }, ... { ... "Name":[ ... "Bob", ... "Mike" ... ] ... }, ... { ... "Name":[ ... "Carol", ... "Sam" ... ] ... }, ... { ... "Name":[ ... "David", ... "John" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5d1d8f22064be7ab44e7f9") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo389.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e5d1d8f22064be7ab44e7f9"), "details" : [ { "Name" : [ "Chris", "David" ] }, { "Name" : [ "Bob", "Mike" ] }, { "Name" : [ "Carol", "Sam" ] }, { "Name" : [ "David", "John" ] } ] }
ต่อไปนี้เป็นแบบสอบถามเพื่อดึงค่าทั้งหมด -
> db.demo389.aggregate([ ... { ... $unwind: "$details" ... }, ... { ... $unwind: "$details.Name" ... }, ... { ... $project: { ... "_id": "$_id", ... "Name": "$details.Name" ... } ... }, ... { ... $group: { ... _id: "_id", ... out: { ... $push: "$Name" ... } ... } ... }, ... { ... $project: { ... "_id": 0, ... "NameArray": "$out" ... } ... } ... ])
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "NameArray" : [ "Chris", "David", "Bob", "Mike", "Carol", "Sam", "David", "John" ] }