Sử dụng tùy chọn upsert: true trong update() (hoặc updateOne()/updateMany()) để thực hiện "insert nếu không tồn tại, update nếu đã tồn tại".
Ví dụ: Collection onlyInsertIfValueIsUniqueDemo:
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Larry","StudentAge":22});
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Mike","StudentAge":21});
> db.onlyInsertIfValueIsUniqueDemo.insertOne({"StudentName":"Sam","StudentAge":24});
Trường hợp 1: Giá trị đã tồn tại (Mike) -> UPDATE:
> db.onlyInsertIfValueIsUniqueDemo.update(
{ StudentName: "Mike" },
{ $set: { "StudentAge": 27 } },
{ upsert: true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Kết quả: Tuổi Mike từ 21 thành 27.
Trường hợp 2: Giá trị mới (David) -> INSERT:
> db.onlyInsertIfValueIsUniqueDemo.update(
{ StudentName: "David" },
{ $set: { "StudentAge": 25 } },
{ upsert: true }
);
WriteResult({ "nMatched": 0, "nUpserted": 1, "nModified": 0, "_id": ObjectId("...") })
Kết quả: Tài liệu David mới được chèn.
Lưu ý:
- Cần có index unique trên trường điều kiện (StudentName) để đảm bảo tính duy nhất thực sự.
- MongoDB 3.2+: Dùng
updateOne()/updateMany()vớiupsert: true. replaceOne()vớiupsert: truethay thế toàn bộ tài liệu.