Changing the primary key on a MongoDB collection?


To change the primary key, you need to first delete it. Use forEach() along with delete to remove and then get a new primary key. Let us create a collection with documents −

> db.demo41.insertOne({"StudentName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25ce4acfb11e5c34d898e3")
}

Display all documents from a collection with the help of find() method −

> db.demo41.find();

This will produce the following output −

{ "_id" : ObjectId("5e25ce4acfb11e5c34d898e3"), "StudentName" : "Carol" }

Here is the query to change the primary key on a MongoDB collection −

> var next = db.demo41.find()
>
> next.forEach(function(s) {
...    var prevId=s._id;
...    delete s._id;
...    db.demo41.insert(s);
...    db.demo41.remove(prevId);
... });

Let us check the primary key once again −

> db.demo41.find();

This will produce the following output displaying a new primary key −

{ "_id" : ObjectId("5e25cee5cfb11e5c34d898e4"), "StudentName" : "Carol" }

Updated on: 02-Apr-2020

948 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements