Building Multiple Indexes at once in MongoDB?

To build multiple indexes at once in MongoDB, use the createIndexes() method and pass multiple index specifications in an array. This approach is more efficient than creating indexes one by one.

Syntax

db.collection.createIndexes([
    { "field1": 1 },
    { "field2": -1 },
    { "field3": 1, "field4": 1 }
]);

Example

Let's create multiple single-field indexes on a collection ?

db.multipleIndexesDemo.createIndexes([
    {"First": 1},
    {"Second": 1},
    {"Third": 1},
    {"Fourth": 1},
    {"Fifth": 1}
]);
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 6,
    "ok": 1
}

Verify Created Indexes

Use getIndexes() to view all indexes on the collection ?

db.multipleIndexesDemo.getIndexes();
[
    {
        "v": 2,
        "key": {
            "_id": 1
        },
        "name": "_id_",
        "ns": "test.multipleIndexesDemo"
    },
    {
        "v": 2,
        "key": {
            "First": 1
        },
        "name": "First_1",
        "ns": "test.multipleIndexesDemo"
    },
    {
        "v": 2,
        "key": {
            "Second": 1
        },
        "name": "Second_1",
        "ns": "test.multipleIndexesDemo"
    },
    {
        "v": 2,
        "key": {
            "Third": 1
        },
        "name": "Third_1",
        "ns": "test.multipleIndexesDemo"
    },
    {
        "v": 2,
        "key": {
            "Fourth": 1
        },
        "name": "Fourth_1",
        "ns": "test.multipleIndexesDemo"
    },
    {
        "v": 2,
        "key": {
            "Fifth": 1
        },
        "name": "Fifth_1",
        "ns": "test.multipleIndexesDemo"
    }
]

Key Points

  • createIndexes() creates all indexes in a single operation, which is more efficient than multiple createIndex() calls.
  • The method returns the total number of indexes before and after the operation.
  • Each index gets an auto-generated name like fieldName_1 for ascending indexes.

Conclusion

Use createIndexes() with an array of index specifications to efficiently create multiple indexes simultaneously. This approach reduces overhead compared to creating indexes individually and provides better performance during bulk index creation.

Updated on: 2026-03-15T00:40:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements