ใช้ตัวดำเนินการ $set พร้อมสัญลักษณ์จุด (dot notation) เพื่อเพิ่มฟิลด์ใหม่เข้าไปในซับดอกิวเมนต์ ไวยากรณ์ดังนี้:
db.yourCollectionName.update(
{"_id" : yourObjectId},
{$set: { "yourOuterFieldName.anyInnerFieldName": yourValue}}
);
สร้างคอลเลกชันตัวอย่าง:
> db.pushNewKeyDemo.insertOne({"UserId":100,"UserDetails":{}});
{ "acknowledged" : true, "insertedId" : ObjectId("5cda58f5b50a6c6dd317adbf") }
แสดงเอกสาร (UserDetails เป็นออบเจกต์ว่าง):
> db.pushNewKeyDemo.find();
{ "_id" : ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId" : 100, "UserDetails" : { } }
คิวรี่เพิ่มฟิลด์ UserName เข้าไปใน UserDetails:
> db.pushNewKeyDemo.update(
{"_id" : ObjectId("5cda58f5b50a6c6dd317adbf")},
{$set: { "UserDetails.UserName": "David Miller"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
ตรวจสอบเอกสารอีกครั้ง:
> db.pushNewKeyDemo.find();
{ "_id" : ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId" : 100, "UserDetails" : { "UserName" : "David Miller" } }
เทคนิค: ใช้ dot notation (UserDetails.UserName) เพื่อระบุเส้นทางไปยังฟิลด์ย่อยภายในออบเจกต์ ถ้าฟิลด์ยังไม่มีอยู่ จะถูกสร้างขึ้นใหม่อัตโนมัติ