Để cập nhật tài liệu hiện có, dùng phương thức update(). Cú pháp:
db.yourCollectionName.update(yourExistingValue, yourUpdatedValue);
Tạo collection updateInformation:
> db.updateInformation.insert({"StudentName":"Larry",StudentAge:35,StudentMarks:89});
WriteResult({ "nInserted" : 1 })
Hiển thị:
> db.updateInformation.find();
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 35, "StudentMarks" : 89 }
Cập nhật StudentAge từ 35 thành 24:
> db.updateInformation.update({StudentAge:35},{$set:{StudentAge:24}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kiểm tra lại:
> db.updateInformation.find().pretty();
{ "_id" : ObjectId("5c6aa29a64f3d70fcc9147f7"), "StudentName" : "Larry", "StudentAge" : 24, "StudentMarks" : 89 }
Trường StudentAge đã cập nhật từ 35 thành 24.