Open In App

How to Set a Primary Key in MongodDB?

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, 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.



Understanding Primary Keys in MongoDB

Methods for Setting Primary Keys

There are several methods for setting primary keys in MongoDB:

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.

Article Tags :