

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Update _id field in MongoDB
To update, just save new ID and remove the old one using remove(). Let us first create a collection with documents −
> db.updatingDemo.insertOne({"StudentName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04dae5150ee0e76c06a04b") } > db.updatingDemo.insertOne({"StudentName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e04dae7150ee0e76c06a04c") }
Following is the query to display all documents from a collection with the help of find() method −
> db.updatingDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e04dae5150ee0e76c06a04b"), "StudentName" : "Robert" } { "_id" : ObjectId("5e04dae7150ee0e76c06a04c"), "StudentName" : "Bob" }
Here is the query to update _id in MongoDB −
> myDocument = db.updatingDemo.findOne({"StudentName":"Bob"}); { "_id" : ObjectId("5e04dae7150ee0e76c06a04c"), "StudentName" : "Bob" } > myDocument._id = 1001; 1001 > db.updatingDemo.insert(myDocument); WriteResult({ "nInserted" : 1 }) > db.updatingDemo.remove({_id:ObjectId("5e04dae7150ee0e76c06a04c")}); WriteResult({ "nRemoved" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.updatingDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e04dae5150ee0e76c06a04b"), "StudentName" : "Robert" } { "_id" : 1001, "StudentName" : "Bob" }
- Related Questions & Answers
- Hide id field in MongoDB
- Update MongoDB field using value of another field?
- How to update _id field in MongoDB?
- Update field in exact element array in MongoDB?
- Want to update inner field in a MongoDB
- Conditional update depending on field matched in MongoDB
- Update a MongoDB document with Student Id and Name
- MongoDB query to update array with another field?
- MySQL UPDATE query where id is highest AND field is equal to variable?
- Convert a field to an array using MongoDB update operation?
- Querying only the field name and display only the id in MongoDB?
- Convert a field to an array using update operation in MongoDB
- How to update a single field in a capped collection in MongoDB?
- MongoDB query to update field and modify the data currently in column
- Update salary field value with 10 percent of each employee in MongoDB
Advertisements