Reputation: 228
I want to update my _id field in one of the document ( shown below ).
{
_id : ObjectId("586d9d5d23352af1a4aa05f7"),
name: "Soham",
age : 99,
city : "XYZ"
}
So I ran the below steps:
var doc = db.names.find({name:"Soham"});
doc._id = 111 ; -- 111 is not present in that collection for any document
db.names.remove({_id:ObjectId("586d9d5d23352af1a4aa05f7")});
db.names.insert(doc);
The first 3 lines haven't threw any error, but the moment I ran the insert command, it threw error. Can anyone please let me know what's going wrong.
Thanks in advance!!!
Upvotes: 1
Views: 7113
Reputation: 5529
Is throwing an error, because you can't update the _id field.
In order to set a new id, first you find the document (using findOne, since you search just for 1 document), than need to create a new document with new id and insert it, than we can safe delete the old:
var doc = db.names.find_one({name:"Soham"});
doc._id = 111 ;
db.names.insert(doc);
db.names.remove({_id:ObjectId("586d9d5d23352af1a4aa05f7")});
Upvotes: 5