Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to update _id field in MongoDB?
You can't directly update the _id field in MongoDB using standard update operations. The _id field is immutable once a document is created. However, you can achieve this by creating a new document with the desired _id and removing the old one.
Syntax
// Step 1: Find and store the document
var document = db.collection.findOne({field: "value"});
// Step 2: Change the _id
document._id = newIdValue;
// Step 3: Save as new document
db.collection.save(document);
// Step 4: Remove the old document
db.collection.remove({_id: oldIdValue});
Sample Data
Let's create a collection with a sample document ?
db.updatingIdFieldDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce271bb36e8b255a5eee949")
}
db.updatingIdFieldDemo.find();
{ "_id" : ObjectId("5ce271bb36e8b255a5eee949"), "StudentName" : "Chris" }
Example: Update _id Field
Here's how to change the _id from ObjectId to a simple integer value ?
var myDocument = db.updatingIdFieldDemo.findOne({StudentName:"Chris"});
myDocument._id = 101;
db.updatingIdFieldDemo.save(myDocument);
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 })
Now remove the old document with the original ObjectId ?
db.updatingIdFieldDemo.remove({_id:ObjectId("5ce271bb36e8b255a5eee949")});
WriteResult({ "nRemoved" : 1 })
Verify Result
db.updatingIdFieldDemo.find();
{ "_id" : 101, "StudentName" : "Chris" }
Key Points
- The
_idfield cannot be modified with$setor other update operators. - The
save()method creates a new document when the _id doesn't exist. - Always remove the old document to avoid duplicates.
Conclusion
Updating the _id field requires a workaround: retrieve the document, modify its _id, save it as new, and remove the original. This effectively "updates" the _id by replacing the entire document.
Advertisements
