- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to update _id field in MongoDB?
You can’t directly update _id field i.e. write some script to update. Let us first create a collection with documents −
> db.updatingIdFieldDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5ce271bb36e8b255a5eee949") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updatingIdFieldDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce271bb36e8b255a5eee949"), "StudentName" : "Chris" }
Following is the query to update _id field in MongoDB −
> var myDocument=db.updatingIdFieldDemo.findOne({StudentName:"Chris"}); > myDocument._id = 101; 101 > db.updatingIdFieldDemo.save(myDocument); WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 }) > db.updatingIdFieldDemo.remove({_id:ObjectId("5ce271bb36e8b255a5eee949")}); WriteResult({ "nRemoved" : 1 })
Let us check the records once again −
> db.updatingIdFieldDemo.find();
This will produce the following output. We have successfully updated _id −
{ "_id" : 101, "StudentName" : "Chris" }
Advertisements