MongoDB Advanced Indexing - MongoDB

What is advanced indexing in MongoDB?

Consider below document of the users collection

Above document will contain an address sub-document and a tags array.

Indexing Array Fields

Assume that you want to search user documents based on the user’s tags. For this, create an index on tags array in the collection.

Creating an index on array in turn will create a separate index entries for each of its fields. Therefore when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs.

To create an index on tags array, use below code

After creating the index, you can search on the tags field of the collection like this

To check that proper indexing is being used, use explain command as shown below

Above command results in "cursor" : "BtreeCursor tags_1" which confirms that proper indexing is used.

Indexing Sub-Document Fields

Assume that you want to search documents based on city, state and pincode fields. As all these fields are part of address sub-document field, create an index on all the fields of the sub-document.
To create an index on all the 3 fields of the sub-document, use below code

Once the index is created, you can search for any of the sub-document fields using this index as shown below

Note that the query expression should follow the order of the index specified. Therefore the index created above will support below queries

It will also support below query

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics