Creating an index on a nested MongoDB field?


You can use dot(.) notation for this. Let us first create a collection with documents −

> db.createIndexOnNestedFieldDemo.insertOne(
   {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"John","UserLastName":"Smith"}}});
   {
      "acknowledged" : true,
      "insertedId" : ObjectId("5ce929c778f00858fb12e916")
   }
>
> db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"Chris","UserLastName":"Brown"}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce929d678f00858fb12e917")
}
> db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"David","UserLastName":"Miller"}}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce929e378f00858fb12e918")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.createIndexOnNestedFieldDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ce929c778f00858fb12e916"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "John",
         "UserLastName" : "Smith"
      }
   }
}
{
   "_id" : ObjectId("5ce929d678f00858fb12e917"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "Chris",
         "UserLastName" : "Brown"
      }
   }
}
{
   "_id" : ObjectId("5ce929e378f00858fb12e918"),
   "UserDetails" : {
      "UserPersonalDetails" : {
         "UserFirstName" : "David",
         "UserLastName" : "Miller"
      }
   }
}

Following is the query to create an index on a nested field −

>db.createIndexOnNestedFieldDemo.createIndex({"UserDetails.UserPersonalDetails.UserLastName":1});

This will produce the following output −

{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
raja
Published on 14-Jun-2019 15:46:19
Advertisements