เพื่อสืบค้นเอกสารฝังตัวใน 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 } ] }
คำสั่งสำหรับสืบค้นเอกสารฝังตัว (กรองอายุ 21 ขึ้นไป)
> 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 } }