ในการสืบค้นเอกสารที่ฝังใน MongoDB ให้ใช้ aggregate() ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo705.insertOne(
... {
... _id:101,
... "Information":
... [
... {
... "StudentName":"Chris",
... "StudentAge":21
... },
... {
... "StudentName":"David",
... "StudentAge":23
... },
... {
... "StudentName":"Bob",
... "StudentAge":20
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 } แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo705.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 101, "Information" : [ { "StudentName" : "Chris", "StudentAge" : 21 }, { "StudentName" : "David", "StudentAge" : 23 }, { "StudentName" : "Bob", "StudentAge" : 20 } ] } ต่อไปนี้เป็นวิธีการสืบค้นเอกสารที่ฝังใน MongoDB -
> db.demo705.aggregate(
... { $unwind: '$Information' },
... { $match: {'Information.StudentAge': {$gte: 21}}},
... { $project: {Information: 1}}
... ) สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 101, "Information" : { "StudentName" : "Chris", "StudentAge" : 21 } }
{ "_id" : 101, "Information" : { "StudentName" : "David", "StudentAge" : 23 } }