ในการดึงวัตถุที่ซ้อนกันใน MongoDB ให้ใช้ตัวดำเนินการ $ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.queryNestedObject.insertOne(
... {
... "StudentName" : "James",
... "StudentSubjectScore" : [
... {"StudentMongoDBScore":98},
... {"StudentCScore":92},
... {"StudentJavaScore":91}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccf49a9dceb9a92e6aa1962")
} ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.queryNestedObject.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{
"_id" : ObjectId("5ccf49a9dceb9a92e6aa1962"),
"StudentName" : "James",
"StudentSubjectScore" : [
{
"StudentMongoDBScore" : 98
},
{
"StudentCScore" : 92
},
{
"StudentJavaScore" : 91
}
]
} ต่อไปนี้เป็นแบบสอบถามเพื่อดึงวัตถุที่ซ้อนกัน -
> db.queryNestedObject.find({'StudentSubjectScore.StudentJavaScore' : 91},{'StudentSubjectScore.$': 1 , _id: 0}); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "StudentSubjectScore" : [ { "StudentJavaScore" : 91 } ] }