คุณสามารถใช้ตัวดำเนินการ $elemMatch สำหรับสิ่งนี้ ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -
> db.pushNewItemsDemo.insertOne(
{
"_id" :1,
"StudentScore" : 56,
"StudentOtherDetails" : [
{
"StudentName" : "John",
"StudentFriendName" : [
"Bob",
"Carol"
]
},
{
"StudentName" : "David",
"StudentFriendName" : [
"Mike",
"Sam"
]
}
]
}
);
{ "acknowledged" : true, "insertedId" : 1 } ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -
> db.pushNewItemsDemo.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] } ต่อไปนี้เป็นแบบสอบถามเพื่อส่งรายการใหม่ไปยังอาร์เรย์ภายในวัตถุ -
>db.pushNewItemsDemo.update({"_id":1,"StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}},
{"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) ให้เราตรวจสอบเอกสารอีกครั้ง -
> db.pushNewItemsDemo.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }