MongoDB - Advanced Indexing

MongoDB - Advanced Indexing In this chapter will learn the Indexing Array Fields and Indexing Sub-Document Fields

Assume the following user collection -

    "address": {
        "city": "France",
        "state": "Paris",
        "pincode": "75008"
    "tags": [
        "owner "
    "name": "David"
Here document contains an address sub-document and a tags array.

Indexing Array Fields

Assume we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection. Creating an index on array in turn creates separate index entries for each of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values travel, cook and owner. To create an index on tags array, use the following code

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

To verify that proper indexing is used, use the following explain command

At last "cursor" : "BtreeCursor tags_1" which confirms that proper indexing is used.


Indexing Sub-Document Fields

Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document. for making an index on all the three fields of the sub-document, use the following code. when the index is created, we can search for any of the sub-document fields utilizing this index as follows

So the index created above would support the following queries −
It will look link query -

Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.