Build index in the background with MongoDB

To create index in the background, use createIndex() method and set "background: true" as the second parameter. Background indexing allows MongoDB to build indexes without blocking database operations.

Syntax

db.collectionName.createIndex(
    {"fieldName1": 1, "fieldName2": 1},
    {background: true}
);

Example

Let us create a compound index on StudentName and StudentAge fields in the background ?

db.indexCreationDemo.createIndex(
    {"StudentName": 1, "StudentAge": 1},
    {background: true}
);
{
    "createdCollectionAutomatically": true,
    "numIndexesBefore": 1,
    "numIndexesAfter": 2,
    "ok": 1
}

Verify the Index

Display all indexes to confirm the background index was created ?

db.indexCreationDemo.getIndexes();
[
    {
        "v": 2,
        "key": {
            "_id": 1
        },
        "name": "_id_",
        "ns": "web.indexCreationDemo"
    },
    {
        "v": 2,
        "key": {
            "StudentName": 1,
            "StudentAge": 1
        },
        "name": "StudentName_1_StudentAge_1",
        "ns": "web.indexCreationDemo",
        "background": true
    }
]

Key Points

  • Background indexing allows other database operations to continue during index creation
  • The created index shows "background": true in its metadata
  • Foreground indexing is faster but blocks all operations on the collection

Conclusion

Use the background: true option with createIndex() to build indexes without blocking database operations. This is essential for production environments where uptime is critical.

Updated on: 2026-03-15T01:46:19+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements