ใช้ $set เพิ่ม Field ใหม่ในเอกสารที่มีอยู่
โอเปอเรเตอร์ $set สามารถเพิ่มฟิลด์ใหม่หรืออัปเดทฟิลด์เดิมได้ โดยไม่กระทบฟิลด์อื่นในเอกสารเดียวกัน
ตัวอย่างข้อมูล
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Chris","ClientAge":34});
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Robert","ClientAge":36});
คำสั่งเพิ่ม ClientDetails.ClientCountryName ให้ทุกเอกสาร (ค่าเริ่มต้นว่าง)
> db.addAFieldToEveryRecordDemo.update(
{},
{ $set: { "ClientDetails.ClientCountryName": "" } },
true, // upsert
true // multi
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
ผลลัพธ์: ทุกเอกสารมี ClientDetails.ClientCountryName = ""
> db.addAFieldToEveryRecordDemo.find().pretty();
{ "_id" : ObjectId("5cd00e32588d4a6447b2e061"), "ClientName" : "Chris", "ClientAge" : 34, "ClientDetails" : { "ClientCountryName" : "" } }
{ "_id" : ObjectId("5cd00e59588d4a6447b2e062"), "ClientName" : "Robert", "ClientAge" : 36, "ClientDetails" : { "ClientCountryName" : "" } }
พารามิเตอร์ของ update() แบบ Legacy (4 พารามิเตอร์)
db.collection.update(
, // Filter
, // Update Document ($set, $inc, etc.)
, // true = insert if not found
// true = update all matching, false = update one
);
รูปแบบสมัยใหม่ (MongoDB 3.2+) - แนะนำ
// เพิ่มฟิลด์ให้ทุกเอกสาร
db.addAFieldToEveryRecordDemo.updateMany(
{},
{ $set: { "ClientDetails.ClientCountryName": "" } }
);
// เพิ่มฟิลด์ให้เอกสารเดียว
db.addAFieldToEveryRecordDemo.updateOne(
{ ClientName: "Chris" },
{ $set: { "ClientDetails.ClientCountryName": "Thailand" } }
);
// Upsert: เพิ่มถ้าไม่มี
db.addAFieldToEveryRecordDemo.updateOne(
{ ClientName: "NewUser" },
{ $set: { "ClientDetails.ClientCountryName": "Thailand" } },
{ upsert: true }
);
Nested Field ด้วย Dot Notation
"ClientDetails.ClientCountryName"- สร้าง Object ClientDetails ถ้ายังไม่มี แล้วเพิ่ม ClientCountryName เข้าไป- Deep Nesting:
"level1.level2.level3.field" - Array Element:
"arr.0.field"(Index เฉพาะ)
สรุป
- ใช้
$setเพิ่ม/แก้ไขฟิลด์ - ปลอดภัย ไม่ทับฟิลด์อื่น - ใช้
updateMany({}, ...)สำหรับทุกเอกสาร - ใช้
updateOne()สำหรับเอกสารเดียว - Dot Notation สร้าง Nested Object อัตโนมัติ