How to Set a Primary Key in MongoDB?
Last Updated :
08 Jul, 2024
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 to set a primary key in MongoDB by providing detailed explanations and examples to understand and implement this concept effectively.
Primary Keys in MongoDB
- In MongoDB, each document within a collection is uniquely identified by a field called the _id field.
- The _id field serves as the primary key for the document, ensuring its uniqueness within the collection.
- MongoDB automatically assigns a unique _id value to each document if one is not provided explicitly.
How to Set a Primary Key in MongoDB?
There are several methods for setting primary keys in MongoDB:
- Using the _id Field: MongoDB automatically assigns a unique value to the _id field if not provided explicitly.
- Custom _id Field: We can specify your own custom _id field with a unique value for each document.
- Unique Index: We can create a unique index on a field to enforce uniqueness and use it as a primary key.
Let's explore each method with examples and outputs.
1. Using the _id Field
MongoDB automatically generates a unique _id value for each document if one is not provided explicitly. Let's see an example:
// Inserting a document without specifying the _id field
db.users.insertOne({ "name": "Alice" });
Output:
{
"_id": ObjectId("6156d8f013c92ec9f5b8b36f"),
"name": "Alice"
}
In this example, MongoDB automatically generates a unique ObjectId value for the _id field.
2. Using Custom _id Field
We can specify our own custom _id value for a document. This value should be unique within the collection to avoid conflicts. Let's see an example:
// Inserting a document with a custom _id field
db.users.insertOne({ "_id": 1001, "name": "Bob" });
Output:
{
"_id": 1001,
"name": "Bob"
}
In this example, we explicitly specify the _id field with the value 1001.
3. Using Unique Index
We can create a unique index on a field to apply uniqueness and use it as a primary key. Let's create a unique index on the email field:
// Creating a unique index on the email field
db.users.createIndex({ "email": 1 }, { unique: true });
Now, when inserting documents, MongoDB will enforce uniqueness on the email field, effectively making it act as a primary key.
Conclusion
Overall, Setting a primary key in MongoDB is essential for uniquely identifying documents within a collection. By understanding the various methods for setting primary keys and their implications, you can design your MongoDB schemas effectively and ensure data integrity within your database. Whether using the default _id field, specifying a custom _id value, or creating unique indexes, MongoDB provides flexibility in setting primary keys based on your application requirements.
What happens if I try to insert a document with a duplicate _id
value?
MongoDB will throw a duplicate key error and the insertion will fail. Each _id
value must be unique within a collection.
Can I change the _id
field of an existing document?
No, the _id
field is immutable once set. To change the _id
, you would need to remove the document and insert a new one with the desired _id
.
Is it possible to have multiple unique indexes in a single collection?
Yes, you can create multiple unique indexes on different fields within the same collection. This allows you to enforce uniqueness on multiple attributes of your documents.
Similar Reads
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 pri
5 min read
How to Deploy a Replica Set in MongoDB?
MongoDB replica sets are crucial for ensuring high availability, fault tolerance, and data redundancy in MongoDB deployments. A replica set is a group of MongoDB instances that maintain the same dataset, offering a reliable solution for production environments.In this article, we will explain the pr
5 min read
How to Use $set and $unset Operators in MongoDB
MongoDB is a NoSQL database that stores data in documents instead of traditional rows and columns found in relational databases. These documents, grouped into collections, allow for flexible data storage and retrieval. One of MongoDBâs key advantages is its ability to dynamically update documents us
6 min read
How to Rename Fields in MongoDB
The $rename operator in MongoDB is a powerful tool used to rename field names within documents. It works by unsetting the old field name and setting the new one by preserving the document's atomicity but altering the field order. This operator is essential for managing and updating document structur
5 min read
How to Search by id in MongoDB
In MongoDB, each document in a collection is uniquely identified by a field called "_id". This "_id" field serves as the primary key and provides a unique identifier for each document. Searching by ID is a common operation in MongoDB and allows us to retrieve specific documents based on their unique
4 min read
How to Register Schema in Mongoose?
In Mongoose, schema registration is a crucial step in defining the structure of our MongoDB documents. In this article, We will go through the process of registering a schema in Mongoose by providing various methods with implementation to efficiently manage our data models. How to register Schema in
3 min read
How to Set Username and Password in MongoDB Compass
In MongoDB, authentication is not enabled by default, which means anyone can access the database. To enhance security, especially in production environments, it is essential to create users with specific roles and permissions. In this article, We will go through setting up a username and password in
3 min read
How to Read from Secondary Node in MongoDB ?
MongoDB is a powerful NoSQL database that provides high availability and redundancy through replica sets. A replica set consists of multiple MongoDB nodes that maintain the same data set, ensuring fault tolerance and load balancing. By default, all read and write operations go to the primary node, b
4 min read
Replica Set Members in MongoDB
MongoDB is a popular NoSQL database that stores data in documents, which are JSON-like objects. MongoDB is designed to be scalable, high-performance, and flexible. MongoDB can handle various data types, such as structured, semi-structured, or unstructured data. MongoDB also supports features such as
8 min read
How to Start MongoDB Local Server?
MongoDB a NoSQL database, offers a local server environment that allows developers and users to work with MongoDB databases directly on their machines. This local server also known as a single-machine copy of MongoDB is an invaluable tool for various purposes, including development, testing, learnin
4 min read