Open In App

How to Set a Primary Key in MongoDB?

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Using the _id Field: MongoDB automatically assigns a unique value to the _id field if not provided explicitly.
  2. Custom _id Field: We can specify your own custom _id field with a unique value for each document.
  3. 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.


Next Article
Article Tags :

Similar Reads