MongoDB ไม่รองรับการเปลี่ยน __id โดยตรง ต้องลบเอกสารเก่าและแทรกใหม่ (insert) จะได้ _id ใหม่อัตโนมัติ
ตัวอย่างข้อมูลทดสอบ
> db.demo41.insertOne({"StudentName":"Carol"});
แสดงข้อมูลก่อน (มี _id เดิม)
> db.demo41.find();
{
"_id" : ObjectId("5e25ce4acfb11e5c34d898e3"),
"StudentName" : "Carol"
}
คำสั่งเปลี่ยน _id ด้วย forEach
> var next = db.demo41.find()
> next.forEach(function(s) {
var prevId = s._id;
delete s._id;
db.demo41.insert(s);
db.demo41.remove(prevId);
});
ผลลัพธ์หลังเปลี่ยน _id ใหม่
> db.demo41.find();
{
"_id" : ObjectId("5e25cee5cfb11e5c34d898e4"),
"StudentName" : "Carol"
}
คำเตือน: วิธีนี้เหมาะสำหรับข้อมูลน้อย สำหรับข้อมูลมาก ควรใช้ bulkWrite หรือเขียนสคริปต์นำออก-นำเข้า (export/import) แทน เพื่อประสิทธิภาพและความปลอดภัย