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

วิธีใช้ MongoDB Update() กับ $set เพื่ออัปเดตฟิลด์ทั้งหมดในคอลเลกชัน

บทความนี้สาธิตการใช้ update() ร่วมกับ $set และตัวเลือก multi: true เพื่ออัปเดตค่าของฟิลด์เดียวกันในทุกเอกสารที่ตรงกับเงื่อนไข

สร้างข้อมูลตัวอย่าง

> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd506fe2cba06f46efe9efa") }
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd507022cba06f46efe9efb") }
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd507022cba06f46efe9efc") }
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd507032cba06f46efe9efd") }

แสดงข้อมูลก่อนอัปเดต

> db.workingOfUpdateMethod.find().pretty();
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "AUS" }

อัปเดตฟิลด์ ClientCountryName จาก "AUS" เป็น "UK" ในทุกเอกสาร

> db.workingOfUpdateMethod.update(
  { "ClientCountryName" : "AUS" },
  { $set: { "ClientCountryName" : "UK" } },
  { multi: true }
);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })

ตรวจสอบผลลัพธ์หลังอัปเดต

> db.workingOfUpdateMethod.find().pretty();
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "UK" }

คำอธิบายพารามิเตอร์สำคัญ

  • Query criteria: { "ClientCountryName" : "AUS" } - เลือกเอกสารที่มีค่า AUS
  • Update operator: { $set: { "ClientCountryName" : "UK" } } - ตั้งค่าใหม่เป็น UK
  • Options: { multi: true } - สำคัญมาก! ทำให้อัปเดต ทุกเอกสาร ที่ตรงเงื่อนไข (Default คือ false = อัปเดตแค่ตัวแรก)

หมายเหตุสำคัญ

ใน MongoDB เวอร์ชันใหม่ แนะนำให้ใช้ updateMany() แทน update() พร้อม multi: true เพราะ语义 ชัดเจนกว่า:

db.workingOfUpdateMethod.updateMany(
  { "ClientCountryName" : "AUS" },
  { $set: { "ClientCountryName" : "UK" } }
);