Khi dùng _id tùy chỉnh (custom _id), phương thức insert() sẽ báo lỗi trùng khóa (E11000) nếu _id đã tồn tại. Để thực hiện upsert (chèn nếu mới, cập nhật nếu có), dùng update() với upsert: true.
Ví dụ lỗi insert trùng _id:
> db.customIdDemo.insert({ "_id": 1, "StudentName": "John" });
WriteResult({ "nInserted": 1 })
> db.customIdDemo.insert({ "_id": 1, "StudentName": "Carol" });
// Lỗi: E11000 duplicate key error collection: ... _id_ dup key: { : 1.0 }
Giải pháp: Dùng update với upsert:true
> db.customIdDemo.update(
{ "_id": 1 },
{ $set: { "StudentName": "Carol" } },
{ upsert: true }
);
// Nếu _id=1 tồn tại -> update StudentName thành Carol
// Nếu _id=1 không tồn tại -> insert mới { _id: 1, StudentName: "Carol" }
Kết quả sau upsert:
> db.customIdDemo.find().pretty();
{ "_id": 1, "StudentName": "Carol" }
{ "_id": 2, "StudentName": "Carol" }
{ "_id": 3, "StudentName": "Chris" }
Lưu ý: insert() không hỗ trợ upsert. Chỉ update(), updateOne(), updateMany(), replaceOne() mới có tùy chọn upsert.