How to create a nested index in MongoDB?


To create nested index in MongoDB, you can use createIndex() or ensureIndex(). The syntax is as follows −

db.yourCollectionName.createIndex({"yourOuterFieldName.yourInnerFieldName.yourSecondInnerFieldName": 1});

To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.nestedIndexDemo.insertOne(
   ... {
      ...
      ... "CustomerId":101,
      ... "CustomerDetails":
      ... {
         ... "CustomerListDetails":
         ... {
            ... "CustomerName":"Larry",
            ... "CustomerProjectName": "Project-1",
            ... "CustomerCountryName":"US"
         ... }
      ... }
   ... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8fc565d3c9d04998abf010")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c8fc565d3c9d04998abf010"),
   "CustomerId" : 101,
   "CustomerDetails" : {
      "CustomerListDetails" : {
         "CustomerName" : "Larry",
         "CustomerProjectName" : "Project-1",
         "CustomerCountryName" : "US"
      }
   }
}

Here is the query to create a nested index in MongoDB:

> db.nestedIndexDemo.createIndex({"CustomerDetails.CustomerListDetails.CustomerCountryName": 1});
{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

Here is the query to display index −

> db.nestedIndexDemo.getIndexes();

The following is the output −

[
   {
      "v" : 2,
      "key" : {
         "_id" : 1
      },
      "name" : "_id_",
      "ns" : "test.nestedIndexDemo"
   },
   {
      "v" : 2,
      "key" : {
         "CustomerDetails.CustomerListDetails.CustomerCountryName" : 1
      },
      "name" : "CustomerDetails.CustomerListDetails.CustomerCountryName_1",
      "ns" : "test.nestedIndexDemo"
   }
]

Updated on: 30-Jul-2019

343 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements