Để cập nhật trường dựa trên giá trị hiện tại của chính trường đó, dùng find() lặp qua cursor và update() với tham chiếu d.field.
Dữ liệu mẫu
> db.demo115.insertOne({"LastName":"Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2efe9bd8f64a552dae635a") }
Cập nhật thêm tiền tố
> db.demo115.find({"LastName":"Brown"}).forEach(function(d) {
db.demo115.update({_id: d._id}, {$set: {LastName: 'Hello ' + d.LastName}});
})
Kết quả
{ "_id" : ObjectId("5e2efe9bd8f64a552dae635a"), "LastName" : "Hello Brown" }
Giải thích:
find().forEach(): Lặp qua từng document khớpd._id: _id của document hiện tạid.LastName: Giá trị hiện tại của trường LastName'Hello ' + d.LastName: Nối chuỗi trong JavaScript
Cách hiện đại tốt hơn (MongoDB 4.2+): Dùng updateMany với pipeline aggregation:
db.demo115.updateMany(
{"LastName": "Brown"},
[{ $set: { LastName: { $concat: ["Hello ", "$LastName"] } } }]
);
Cách này atomic, nhanh hơn, không cần round-trip client-server. Pipeline update hỗ trợ $set, $unset, $concat, $toLower, etc.