Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

อัปเดต Nested Embedded Documents ใน MongoDB

การอัปเดต Nested Embedded Documents

เพื่ออัปเดต Nested Documents ใน MongoDB ให้ใช้ UPDATE() และ Positional Operator ($)

สร้าง Collection พร้อมข้อมูล

> db.demo643.insertOne({
...     details : [
...         {
...             "CountryName":"US",
...             StudentDetails:[{Name:"Chris"},{SubjectName:"MySQL"}]
...         },
...         {
...             "CountryName":"UK",
...             StudentDetails:[{Name:"Bob"},{SubjectName:"Java"}]
...         }
...     ]
... } ... )
{ "acknowledged" : true, "insertedId" : ObjectId("5e9c737f6c954c74be91e6e3") }

แสดงเอกสารทั้งหมด

> db.demo643.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e9c737f6c954c74be91e6e3"), "details" : [ { "CountryName" : "US", "StudentDetails" : [ { "Name" : "Chris" }, { "SubjectName" : "MySQL" } ] }, { "CountryName" : "UK", "StudentDetails" : [ { "Name" : "Bob" }, { "SubjectName" : "Java" } ] } ] }

คิวรีอัปเดต Nested Embedded Document (เพิ่ม Marks ให้ UK)

> db.demo643.update({"details.CountryName": "UK"}, {"$push": {"details.$.StudentDetails": {Marks:78}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

แสดงเอกสารหลังอัปเดต

> db.demo643.find().pretty();

ผลลัพธ์:

{
    "_id" : ObjectId("5e9c737f6c954c74be91e6e3"),
    "details" : [
        {
            "CountryName" : "US",
            "StudentDetails" : [
                { "Name" : "Chris" },
                { "SubjectName" : "MySQL" }
            ]
        },
        {
            "CountryName" : "UK",
            "StudentDetails" : [
                { "Name" : "Bob" },
                { "SubjectName" : "Java" },
                { "Marks" : 78 }
            ]
        }
    ]
}