Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Friday, 16 February 2024

Difference between Primary key Unique Key in Mongodb

In MongoDB, the concepts of primary keys and unique keys are slightly different from traditional relational database systems. MongoDB uses the _id field as the primary key by default for every document in a collection. Let's explore the differences:

1. Primary Key:

   - In MongoDB, the primary key is the unique identifier for each document in a collection.

   - The primary key field is automatically indexed by MongoDB for fast access.

   - By default, MongoDB uses the _id field as the primary key for each document.

   - You can explicitly specify a different field as the primary key, but this is less common in MongoDB compared to relational databases.

Example:

{

   "_id": ObjectId("617e1d8b493d4e11382c953a"),

   "name": "John Doe",

   "age": 30

}

In this example, _id is the primary key for the document. MongoDB automatically generates a unique ObjectId for the _id field.

2. Unique Index:

   - In MongoDB, unique indexes are used to enforce uniqueness constraints on fields in a collection.

   - You can create unique indexes on one or more fields to ensure that no two documents in a collection have the same values for those fields.

   - Unlike the primary key, unique indexes can be created on fields other than _id.

Example:

Let's say we have a collection of users where we want to ensure that each user has a unique email address:

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

This command creates a unique index on the email field of the users collection, ensuring that no two documents in the collection share the same email address.

In summary, in MongoDB, the primary key is typically the _id field, which uniquely identifies each document. Unique keys are implemented using unique indexes on specific fields to enforce uniqueness constraints.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.