How to Changing the Primary Key in MongoDB Collection
Last Updated :
26 Apr, 2024
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
- A primary key serves as a unique identifier for each document within a MongoDB collection.
- By default, MongoDB uses the _id field as the primary key for documents.
- However, we may encounter situations where we need to change the primary key to a different field or value based on our application's requirements.
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:
- Data Model Changes: Evolving data models may require a different field to serve as the primary key.
- Performance Optimization: Choosing a different field as the primary key may improve query performance.
- Integration with External Systems: Integration with external systems may require aligning the primary key with the key used in other systems.
- Data Migration: During data migration, we may need to update the primary key to match the new data model.
Changing the Primary Key in the MongoDB Collection
To change the primary key in a MongoDB collection, we will need to follow these steps:
- Add a New Field: Add a new field to the documents in the collection to serve as the new primary key.
- Update Existing Documents: Update existing documents to populate the new primary key field.
- Drop the Existing Index: Drop the existing index on the old primary key field.
- Create a New Index: Create a new index on the new primary key field to ensure uniqueness and efficient querying.
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.
Similar Reads
How to Set a Primary Key in MongoDB?
In MongoDB, primary keys play an important role in uniquely identifying documents within a collection. While MongoDB doesn't have a concept of primary keys in the same way as relational databases but it allows for the creation of unique identifiers for documents. In this article, we'll explore how t
3 min read
How to Rename Collection in MongoDB?
Renaming collections in MongoDB is a straightforward operation that helps in maintaining and organizing databases efficiently. MongoDB provides the renameCollection command and the db.collection.renameCollection() method for changing collection names within the same database. In this article, We wil
4 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read
How to Change the Data Store Directory in MongoDB?
In MongoDB, data files are stored by default in the /data/db directory on Unix-like systems and \data\db on Windows. This default setting may not be suitable for all applications particularly large-scale ones or if the default drive lacks sufficient space. In this article, we will learn about How to
3 min read
How to Get the Latest Record from MongoDB Collection
Retrieving the latest record from a MongoDB collection is a common task in many applications. Whether we are building a messaging app, tracking sensor data, or managing user activity getting the most recent data entry is essential for real-time analytics and decision-making. In this article, we'll e
4 min read
What is a collection in MongoDB?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
4 min read
How to Add a Column in MongoDB Collection?
In MongoDB, the ability to add new fields to collections without restructuring the entire schema is a powerful feature. Whether we are adapting to changing requirements or enhancing existing data, MongoDB offers several methods through easily we can easily add new fields to our collections. In this
4 min read
How to add Timestamp in Mongodb Collection using Node.js ?
Timestamp: With the help of timestamp document in the collection of the MongoDB can be differentiated on the basis of time. We can add Timestamp in Mongodb Collection in Node.js using the following approach: Installing Module: Install the mongoose module using the following command: npm install mong
1 min read
How to use TTL collections in MongoDB?
TTL (Time-To-Live) collections in MongoDB is a special collection where it allows automatic deletion of documents after a specified duration. This technique is used in managing temporary data, such as user sessions cache logsHow TTL WorksTTL Index: You create a TTL index on a date field in your coll
5 min read
How to sort collection of MongoDB Database in ascending order using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read