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

แก้ไข Error 'multi update only works with $ operators' ใน MongoDB

แก้ไขข้อผิดพลาด Multi Update ต้องใช้ $ Operators

ข้อผิดพลาด "multi update only works with $ operators" เกิดขึ้นเมื่อ Update หลาย Document โดยไม่ใช้ Update Operator (เช่น $set, $inc, $push)

รูปแบบที่ถูกต้อง: ใช้ $set

db.yourCollectionName.update({ }, { '$set': { "yourFieldName": "yourValue" } }, false, true);

พารามิเตอร์: { } = เงื่อนไข (ว่าง = ทุก Document), { '$set': {...} } = Update Operator, false = upsert, true = multi

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

> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Larry","ClientAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb7372f684a30fbdfd557") }
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Mike","ClientAge":26});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb73f2f684a30fbdfd558") }
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Sam","ClientAge":27});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb7462f684a30fbdfd559") }
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Carol","ClientAge":29});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb7502f684a30fbdfd55a") }

Update ทุก Document ให้ ClientName = "Robert"

> db.unconditionalUpdatesDemo.update({ }, { '$set': { "ClientName": "Robert" }}, false, true);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })

ตรวจสอบผลลัพธ์

> db.unconditionalUpdatesDemo.find().pretty();
{ "_id" : ObjectId("5c8eb7372f684a30fbdfd557"), "ClientName" : "Robert", "ClientAge" : 24 }
{ "_id" : ObjectId("5c8eb73f2f684a30fbdfd558"), "ClientName" : "Robert", "ClientAge" : 26 }
{ "_id" : ObjectId("5c8eb7462f684a30fbdfd559"), "ClientName" : "Robert", "ClientAge" : 27 }
{ "_id" : ObjectId("5c8eb7502f684a30fbdfd55a"), "ClientName" : "Robert", "ClientAge" : 29 }

ClientName ของทุก Document ถูกเปลี่ยนเป็น "Robert" แล้ว