Open In App

How to Changing the Primary Key in MongoDB Collection

In MongoDB, the primary key uniquely identifies each document within a collection. While MongoDB automatically assigns a primary key using the _id field, there may be scenarios where we need to change the primary key to a different field or value.

In this article, we’ll explore how to change the primary key in a MongoDB collection by providing detailed explanations, and examples to understand and implement this process effectively.



Understanding Primary Keys in MongoDB

Reasons for Changing the Primary Key

There are several reasons due to which we might need to change the primary key in a MongoDB collection:

Changing the Primary Key in the MongoDB Collection

To change the primary key in a MongoDB collection, we will need to follow these steps:



Step-by-Step Guide to Changing the Primary Key

Let’s set up an Environment:

To understand How to Changing the Primary Key in MongoDB Collection we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called users which contains the information shown below:

{ "_id": 1, "name": "Alice", "age": 30, "city": "New York" }
{ "_id": 2, "name": "Bob", "age": 35, "city": "San Francisco" }
{ "_id": 3, "name": "Charlie", "age": 25, "city": "Seattle" }
{ "_id": 4, "name": "David", "age": 40, "city": "Los Angeles" }
{ "_id": 5, "name": "Eve", "age": 45, "city": "Chicago" }

1. Add a New Field

Let’s add a new field to the documents in the collection to serve as the new primary key. In this example, we’ll add a field named username as the new primary key.

db.users.updateMany({}, { $set: { username: "" } });

Output:

[
{ _id: 1, name: 'Alice', age: 30, city: 'New York', username: '' },
{ _id: 2, name: 'Bob', age: 35, city: 'San Francisco', username: '' },
{ _id: 3, name: 'Charlie', age: 25, city: 'Seattle', username: '' },
{ _id: 4, name: 'David', age: 40, city: 'Los Angeles', username: '' },
{ _id: 5, name: 'Eve', age: 45, city: 'Chicago', username: '' }
]

Explanation: This query uses the updateMany method to add a new field username to all documents in the users collection with an initial value of an empty string.

2. Update Existing Documents

Next, update existing documents to populate the new primary key field. We can use a unique value from an existing field or generate new unique values.

db.users.find().forEach(function(user) {
db.users.updateOne(
{ _id: user._id },
{ $set: { username: user.name.toLowerCase().replace(" ", "_") } }
);
});

Output:

{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }

Explanation: This query uses the forEach method to iterate over all documents in the users collection. For each document, it updates the username field with a unique value derived from the name field and converting the name to lowercase and replacing spaces with underscores

3. Drop the Existing Index

Drop the existing index on the old primary key field (_id).

db.users.dropIndex("_id_");

Output:

{ "nIndexesWas" : 2, "ok" : 1 }

Explanation: This query drops the existing index on the _id field, which was the default unique index created by MongoDB for the _id field

4. Create a New Index

Create a new index on the new primary key field (username).

db.users.createIndex({ username: 1 }, { unique: true });

Output:

[
{ v: 2, key: { username: 1 }, name: 'username_1', unique: true }
]

Explanation: This query creates a new index on the username field with the unique: true option, ensuring that each username value is unique within the collection

Example of Changing the Primary Key

// Add a new field
db.users.updateMany({}, { $set: { username: "" } });

// Update existing documents
db.users.find().forEach(function(user) {
db.users.updateOne(
{ _id: user._id },
{ $set: { username: user.name.toLowerCase().replace(" ", "_") } }
);
});

// Drop the existing index
db.users.dropIndex("_id_");

// Create a new index
db.users.createIndex({ username: 1 }, { unique: true });

Conclusion

Overall, Changing the primary key in a MongoDB collection involves adding a new field, updating existing documents, dropping the existing index, and creating a new index on the new primary key field. By following the step-by-step guide and understanding the concepts explained in this article, you can effectively change the primary key in your MongoDB collection based on your application’s requirements.


Article Tags :