Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cập nhật trường _id trong MongoDB

Không thể cập nhật _id trực tiếp. Cách thay thế: đọc document, gán _id mới, insert bản sao, xóa bản cũ. Tạo collection:

> db.updatingDemo.insertOne({"StudentName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04dae5150ee0e76c06a04b") }
> db.updatingDemo.insertOne({"StudentName":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04dae7150ee0e76c06a04c") }

Hiển thị tài liệu:

> db.updatingDemo.find();

Quy trình thay đổi _id của "Bob" thành 1001:

> myDocument = db.updatingDemo.findOne({"StudentName":"Bob"});
{ "_id" : ObjectId("5e04dae7..."), "StudentName" : "Bob" }
> myDocument._id = 1001;
1001
> db.updatingDemo.insert(myDocument);
WriteResult({ "nInserted" : 1 })
> db.updatingDemo.remove({_id:ObjectId("5e04dae7150ee0e76c06a04c")});
WriteResult({ "nRemoved" : 1 })

Kết quả - _id đã thay đổi từ ObjectId sang số:

{ "_id" : ObjectId("5e04dae5..."), "StudentName" : "Robert" }
{ "_id" : 1001, "StudentName" : "Bob" }

Cảnh báo: Cách này không an toàn cho production (race condition, mất atomicity). Nên thiết kế schema dùng trường riêng làm khóa nghiệp vụ, giữ _id do MongoDB sinh tự động.