MongoDB - Advanced Indexing

Consider the following document from the users collection −
{ "address" : { "city" : "Los Angeles" , "state" : "California" , "pincode" : "123" }, "tags" : [ "music" , "cricket" , "blogs" ], "name" : "Tom Benzamin" }
The above document contains an address subdocument and an array of tags .
Indexing array fields
Suppose we want to search user documents based on user tags. To do this, we will create an index on an array of tags in the collection.
Creating an index on an array, in turn, creates separate index entries for each of its fields. So in our case, when we create an index on the tags array, separate indexes will be created for its music, cricket, and blog values.
To create an index on an array of tags, use the following code −
> db . users . ensureIndex ({ "tags" : 1 })
After creating the index, we can search in the collection tags field like this:
> db . users . find ({ tags : "cricket" })
To ensure that the correct indexing is being used, use the following explain command −
> db . users . find ({ tags : "cricket" }). explain ()
The above command resulted in a "cursor": "BtreeCursor tags_1", which confirms that the correct indexing is being used.
Indexing Subdocument Fields
Let's say we want to search documents by city, state, and pin code fields. Because all of these fields are part of the subdocument field, we will create an index on all fields in the subdocument.
To create an index on all three fields of a subdocument, use the following code:
> db . users . ensureIndex ({ "address.city" : 1 , "address.state" : 1 , "address.pincode" : 1 })
Once the index is created, we can search for any of the fields in the subdocument using that index as follows:
> db . users . find ({ "address. city" : "Los Angeles" })
Remember that the query expression must follow the order of the specified index. So the index created above will support the following queries:
> db . users . find ({ "address.city" : "Los Angeles" , "address.state" : "California" })
It will also support the following query −