- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" }
- Related Articles
- Update _id field in MongoDB
- How to update the _id of a MongoDB Document?
- Is it possible to rename _id field after MongoDB group aggregation?
- Want to update inner field in a MongoDB
- Update MongoDB field using value of another field?
- How to update a single field in a capped collection in MongoDB?
- MongoDB query to update array with another field?
- How to search document in MongoDB by _id
- Update field in exact element array in MongoDB?
- How to run MongoDB query to update only a specific field value?
- Conditional update depending on field matched in MongoDB
- How to find a record by _id in MongoDB?
- How to delete document by _id using MongoDB?
- How does MongoDB Update() method work to set records of entire field?
- Convert a field to an array using update operation in MongoDB

Advertisements