Không thể cập nhật giá trị trường bằng chính trường đó trực tiếp. Cần sử dụng $set với giá trị tĩnh hoặc biểu thức aggregation (từ MongoDB 4.2+).
Tạo collection:
> db.demo256.insertOne({"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e47a3e91627c0c63e7dba8b") }
> db.demo256.insertOne({"Name":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e47a3ea1627c0c63e7dba8c") }
> db.demo256.insertOne({"Name":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e47a3eb1627c0c63e7dba8d") }
Hiển thị dữ liệu:
> db.demo256.find();
Cập nhật tài liệu đầu tiên: gán chuỗi tĩnh "Name is a student" (KHÔNG sử dụng được giá trị cũ):
> db.demo256.update({}, {$set:{"Name":"Name" + " is a student"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Kết quả: tài liệu đầu tiên thành "Name is a student", 2 tài liệu kia không đổi:
> db.demo256.find();Lưu ý: Từ MongoDB 4.2+, có thể dùng pipeline update với $set: { Name: { $concat: ["$Name", " is a student"] } } để nối chuỗi dựa trên giá trị hiện tại.