เพื่ออัปเดตหรือแก้ไขเอกสารที่มีอยู่ในคอลเล็กชัน MongoDB ใช้เมธอด update() ไวยากรณ์:
db.yourCollectionName.update(yourExistingValue, yourUpdatedValue);
สร้างคอลเล็กชันและเอกสารตัวอย่าง
> db.updateInformation.insert({"StudentName":"Larry", "StudentAge":35, "StudentMarks":89});
WriteResult({ "nInserted" : 1 })
แสดงเอกสารก่อนอัปเดต
> db.updateInformation.find();
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 35, "StudentMarks" : 89 }
อัปเดต StudentAge จาก 35 เป็น 24
> db.updateInformation.update({StudentAge:35}, {$set:{StudentAge:24}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
ใช้ operator $set เพื่อกำหนดค่าใหม่ให้ฟิลด์ที่ต้องการ
ตรวจสอบหลังอัปเดต
> db.updateInformation.find().pretty();
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 24, "StudentMarks" : 89 }
ฟิลด์ StudentAge เปลี่ยนจาก 35 เป็น 24 แล้ว ส่วนฟิลด์อื่นคงเดิม
หมายเหตุ:update()เป็นเมธอดเก่า MongoDB เวอร์ชันใหม่แนะนำใช้updateOne(),updateMany(), หรือreplaceOne()แทน