Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
Updating _id field in MongoDB

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!!!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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")});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!