Creating Unique Indexes
In MongoDB, unique indexes can be created at the collection level using the createIndex() method or by specifying the unique option when defining the index in a collection’s schema.
Example: Creating a Unique Index using createIndex()
// Create a unique index on the "username" field of the "users" collection
db.users.createIndex({ username: 1 }, { unique: true });
In this example, we create a unique index on the “username” field of the “users” collection. The { unique: true } option specifies that the index should apply the uniqueness on the values of the “username” field.
Example: Creating a Unique Index in Schema Definition
When defining a unique index in the schema definition (e.g., with Mongoose in Node.js) we can specify the unique: true option for the field.
const userSchema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
});
In this example, both the “username” and “email” fields are defined as unique in the schema definition, ensuring that documents in the “users” collection have unique values for these fields.
Unique Indexes in MongoDB
MongoDB, a popular NoSQL database offers a range of features to manage data effectively. One such feature is the ability to create unique indexes, which play a crucial role in maintaining data integrity by ensuring that no two documents in a collection have the same value for a specified field or combination of fields.
In this article, we’ll learn the concept of unique indexes in MongoDB by covering their significance, usage, examples, and outputs to help beginners grasp the concept effectively.