MongoDB không cho phép sửa đổi trực tiếp trường _id. Để thay đổi khóa chính, phải xóa tài liệu cũ và chèn lại tài liệu mới (sẽ tự động sinh _id mới).
Tạo collection:
> db.demo41.insertOne({"StudentName":"Carol"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e25ce4acfb11e5c34d898e3") }
Xem _id hiện tại:
> db.demo41.find();
{ "_id" : ObjectId("5e25ce4acfb11e5c34d898e3"), "StudentName" : "Carol" }
Script thay đổi _id (xóa và chèn lại):
> var next = db.demo41.find()
> next.forEach(function(s) {
var prevId=s._id;
delete s._id;
db.demo41.insert(s);
db.demo41.remove(prevId);
});
Kiểm tra _id mới:
> db.demo41.find();
⚠️ Cảnh báo:
- Cách này thay đổi _id của tất cả tài liệu trong collection
- Mất thứ tự chèn gốc (timestamp trong ObjectId)
- Có thể gây lỗi nếu có reference từ collection khác
- Nên dùng
findOneAndReplace()hoặcreplaceOne()cho an toàn hơn
Best practice: Thiết kế _id có ý nghĩa nghiệp vụ (custom _id) ngay từ đầu thay vì để MongoDB tự sinh.