Vấn đề
Cần tạo trường (field) mới cho document đã có sẵn trong collection MongoDB.
Giải pháp: $addToSet hoặc $set
$addToSet: Thêm giá trị vào mảng **chỉ nếu chưa tồn tại** (tránh trùng lặp). Nếu trường chưa có → tạo mảng mới với giá trị đó.$set: Gán giá trị trực tiếp cho trường (tạo mới hoặc ghi đè). Dùng cho trường đơn (không phải mảng).
Ví dụ minh họa với $addToSet
1. Tạo collection và dữ liệu
> db.createFieldDemo.insertOne({"StudentFirstName":"John","StudentAge":21});
> db.createFieldDemo.insertOne({"StudentFirstName":"Larry","StudentAge":23});
> db.createFieldDemo.insertOne({"StudentFirstName":"Chris","StudentAge":22});
> db.createFieldDemo.insertOne({"StudentFirstName":"David","StudentAge":25});
2. Xem dữ liệu ban đầu
> db.createFieldDemo.find().pretty();
3. Thêm trường StudentLastName cho document _id cụ thể
> db.createFieldDemo.update(
{_id: ObjectId("5cd99e43b50a6c6dd317ad98")},
{$addToSet: {"StudentLastName": "Miller"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
4. Kết quả
> db.createFieldDemo.find().pretty();
{ "_id" : ..., "StudentFirstName" : "John", "StudentAge" : 21 }
{ "_id" : ..., "StudentFirstName" : "Larry", "StudentAge" : 23 }
{ "_id" : ..., "StudentFirstName" : "Chris", "StudentAge" : 22 }
{ "_id" : ..., "StudentFirstName" : "David", "StudentAge" : 25, "StudentLastName" : ["Miller"] }
Trường StudentLastName được tạo mới dưới dạng mảng chứa "Miller" chỉ cho document _id khớp.
Lưu ý
$addToSettạo trường kiểu **mảng**. Muốn trường đơn (string) → dùng$set: {"StudentLastName": "Miller"}.- Cập nhật nhiều document: dùng
updateManythayupdate. $setcũng tạo trường mới nếu chưa tồn tại:db.coll.update({}, {$set: {newField: "value"}}, {multi: true}).