Build index in the background with MongoDB

MongoDBDatabaseBig Data Analytics

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
   }
]
raja
Published on 27-Mar-2020 11:31:53
Advertisements