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
Changing the primary key on a MongoDB collection?
To change the primary key in MongoDB, you need to remove the existing _id field and let MongoDB generate a new one. Use forEach() to iterate through documents, delete the current _id, and reinsert the document with a new primary key.
Syntax
db.collection.find().forEach(function(doc) {
var oldId = doc._id;
delete doc._id;
db.collection.insert(doc);
db.collection.remove({_id: oldId});
});
Sample Data
db.demo41.insertOne({"StudentName": "Carol"});
{
"acknowledged": true,
"insertedId": ObjectId("5e25ce4acfb11e5c34d898e3")
}
Display the document to see the current primary key:
db.demo41.find();
{"_id": ObjectId("5e25ce4acfb11e5c34d898e3"), "StudentName": "Carol"}
Example: Change Primary Key
Use forEach() to change the primary key for all documents in the collection:
var cursor = db.demo41.find();
cursor.forEach(function(doc) {
var prevId = doc._id;
delete doc._id;
db.demo41.insert(doc);
db.demo41.remove({_id: prevId});
});
Verify Result
Check that the document now has a new primary key:
db.demo41.find();
{"_id": ObjectId("5e25cee5cfb11e5c34d898e4"), "StudentName": "Carol"}
Key Points
- The
_idfield is immutable once set, so you must delete and recreate the document. - MongoDB automatically generates a new ObjectId when inserting without an
_id. - This operation is not atomic?use with caution in production environments.
Conclusion
Changing primary keys requires deleting the old _id and reinserting the document. MongoDB will automatically assign a new ObjectId, effectively changing the primary key while preserving all other document data.
Advertisements
