Để thêm phần tử vào mảng đã tồn tại trong MongoDB, sử dụng toán tử $addToSet kết hợp với update(). Khác với $push, toán tử $addToSet chỉ thêm phần tử nếu nó chưa tồn tại trong mảng (tránh trùng lặp).
Tạo dữ liệu mẫu
> db.pushElements.insertOne({"Comments":["Good","Awesome","Nice"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd682597924bb85b3f48953") }
Xem dữ liệu ban đầu
> db.pushElements.find().pretty();
Thêm phần tử mới vào mảng
> db.pushElements.update( {_id: ObjectId("5cd682597924bb85b3f48953")}, { "$addToSet": {"Comments": "Cool"} }, upsert=true ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Kết quả
> db.pushElements.find().pretty();So sánh $addToSet vs $push
| Toán tử | Hành vi | Trùng lặp |
|---|---|---|
$addToSet | Thêm nếu chưa có | Tự động loại bỏ |
$push | Luôn thêm vào cuối | Cho phép trùng lặp |
Thêm nhiều phần tử cùng lúc
Sử dụng $each với $addToSet:
db.pushElements.update(
{_id: ObjectId("5cd682597924bb85b3f48953")},
{ "$addToSet": { "Comments": { "$each": ["Cool", "Great", "Excellent"] } } }
);
Thêm phần tử vào vị trí cụ thể
Sử dụng $push với $position (chỉ dùng được với $push):
db.pushElements.update(
{_id: ObjectId("5cd682597924bb85b3f48953")},
{ "$push": { "Comments": { "$each": ["New"], "$position": 0 } } }
); // Thêm vào đầu mảng
Lưu ý
upsert=true: Tạo tài liệu mới nếu không tìm thấy _id- Phiên bản mới: Sử dụng
updateOne()hoặcupdateMany() $addToSetso sánh giá trị hoàn chỉnh (bao gồm kiểu dữ liệu)