ใช้ update() ร่วมกับ $set และ dot notation พร้อม index ของอาร์เรย์ เพื่อเพิ่มฟิลด์ใหม่ในซับดอกิวเมนต์เฉพาะตัว เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:
> db.addExtraFieldDemo.insertOne(
{
"_id": 1,
"UserName": "Larry",
"UserOtherDetails":[
{ "UserCountryName": "US", "UserAge":23 },
{ "UserCountryName": "UK", "UserAge":24 }
]
}
);
{ "acknowledged" : true, "insertedId" : 1 }
แสดงเอกสาร:
> db.addExtraFieldDemo.find().pretty();
คิวรี่เพิ่มฟิลด์ isMarried_ = true ให้กับซับดอกิวเมนต์ตัวแรก (index 0) ใน UserOtherDetails:
> db.addExtraFieldDemo.update( { "_id":1 }, { "$set":{ "UserOtherDetails.0.isMarried_" : true }} ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })ตรวจสอบเอกสารอีกครั้ง:
> db.addExtraFieldDemo.find().pretty();เทคนิค: ใช้
UserOtherDetails.0.isMarried_โดย0คือ index ของอาร์เรย์ (เริ่มจาก 0) วิธีนี้เพิ่มฟิลด์เฉพาะซับดอกิวเมนต์ที่ตำแหน่งที่ระบุเท่านั้น