Build index in the background with MongoDB



To create index in the background, use createIndex() method and set “background: true” as in the below syntax −

db.yourCollectionName.createIndex({"yourFieldName1":1,"yourFieldName2":1},{background: true} );

Let us implement the above syntax in order to create index and set background −

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

Let us display the indexes −

> db.indexCreationDemo.getIndexes();

This will produce the following output −

[    {       "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    } ]
Updated on: 2020-03-27T11:32:25+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements