MongoDB Advanced Indexing

Consider the following document collection (users):

{
   "address": {
      "city": "Los Angeles",
      "state": "California",
      "pincode": "123"
   },
   "tags": [
      "music",
      "cricket",
      "blogs"
   ],
   "name": "Tom Benzamin"
}

The above documents contain an address subdocument and a tags array.


Index Array Fields

Suppose we retrieve users based on tags. For this, we need to create an index on the tags array in the collection.

Creating an index on an array requires building an index for each field in the array sequentially. So when we create an index on the tags array, separate indexes will be created for the three values: music, cricket, and blogs.

Use the following command to create an array index:

>db.users.ensureIndex({"tags":1})

After creating the index, we can retrieve the tags field of the collection like this:

>db.users.find({tags:"cricket"})

To verify that we have used the index, we can use the explain command:

>db.users.find({tags:"cricket"}).explain()

If the execution result of the above command shows "cursor": "BtreeCursor tags_1", it means the index has been used.


Index Subdocument Fields

Suppose we need to retrieve documents by the city, state, and pincode fields. Since these fields are subdocument fields, we need to create an index on the subdocument.

Create an index on the three fields of the subdocument with the following command:

>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})

Once the index is created, we can use the subdocument fields to retrieve data:

>db.users.find({"address.city":"Los Angeles"})   

The query expression does not necessarily follow the order of the specified index; MongoDB will automatically optimize it. So the index created above will support the following queries:

>db.users.find({"address.state":"California","address.city":"Los Angeles"}) 

It also supports the following queries:

>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})
Other Extensions