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 _id field 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.

Updated on: 2026-03-15T02:42:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements