How to create an index with MongoDB?

To create an index in MongoDB, use the createIndex() method (replaces the deprecated ensureIndex()). Indexes improve query performance by creating efficient data lookup structures.

Syntax

db.collection.createIndex(
    { field: 1 },              // 1 for ascending, -1 for descending
    { unique: true }           // optional: index options
);

Create Sample Collection

db.createCollection("creatingUniqueIndexDemo");
{ "ok" : 1 }

Example: Creating a Unique Index

Create a unique index on the UserCountryName field to prevent duplicate country values ?

db.creatingUniqueIndexDemo.createIndex(
    {"UserCountryName": 1}, 
    {unique: true}
);
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}

Insert Sample Data

db.creatingUniqueIndexDemo.insertMany([
    {"UserName": "John", "UserAge": 21, "UserCountryName": "US"},
    {"UserName": "Mike", "UserAge": 23, "UserCountryName": "UK"}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5c9947bd330fd0aa0d2fe4d8"),
        ObjectId("5c9947c9330fd0aa0d2fe4d9")
    ]
}

Testing Unique Constraint

Attempting to insert a document with duplicate UserCountryName "US" will fail ?

db.creatingUniqueIndexDemo.insertOne({
    "UserName": "Robert", 
    "UserAge": 26, 
    "UserCountryName": "US"
});
WriteError: E11000 duplicate key error collection: test.creatingUniqueIndexDemo 
index: UserCountryName_1 dup key: { : "US" }

However, inserting with a unique country value succeeds ?

db.creatingUniqueIndexDemo.insertOne({
    "UserName": "Robert", 
    "UserAge": 26, 
    "UserCountryName": "AUS"
});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c9947e3330fd0aa0d2fe4db")
}

Verify Results

db.creatingUniqueIndexDemo.find().pretty();
{
    "_id" : ObjectId("5c9947bd330fd0aa0d2fe4d8"),
    "UserName" : "John",
    "UserAge" : 21,
    "UserCountryName" : "US"
}
{
    "_id" : ObjectId("5c9947c9330fd0aa0d2fe4d9"),
    "UserName" : "Mike",
    "UserAge" : 23,
    "UserCountryName" : "UK"
}
{
    "_id" : ObjectId("5c9947e3330fd0aa0d2fe4db"),
    "UserName" : "Robert",
    "UserAge" : 26,
    "UserCountryName" : "AUS"
}

Conclusion

Use createIndex() to create indexes in MongoDB. Unique indexes prevent duplicate values and automatically enforce data integrity constraints. Indexes significantly improve query performance on indexed fields.

Updated on: 2026-03-15T00:27:43+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements