MongoDB - Advanced Indexing

MongoDB - Advanced Indexing In this bankruptcy will study the Indexing Array Fields and Indexing Sub-Document Fields

Assume the subsequent user series -

    "deal with": 
        "town": "France",
        "kingdom": "Paris",
        "pincode": "75008"
    "tags": [
        "owner "
    "name": "David"

Here document incorporates an cope with sub-report and a tags array.

Indexing Array Fields

Assume we need to look user files based at the consumer’s tags. For this, we can create an index on tags array within the series. Creating an index on array in turn creates separate index entries for every of its fields. So in our case whilst we create an index on tags array, separate indexes can be created for its values tour, prepare dinner and proprietor. To create an index on tags array, use the following code

After growing the index, we are able to search on the tags field of the collection like this −
>db.Customers.Find(tags:"cook dinner")

To verify that right indexing is used, use the following provide an explanation for command
>db.Customers.Find(tags:"cook dinner").Explain()

At ultimate "cursor" : "BtreeCursor tags_1" which confirms that right indexing is used.

>db.Customers.EnsureIndex("address.Town":1,"address.Nation":1,"cope with.Pincode":1)

Indexing Sub-Document Fields

Suppose that we want to search files based on city, country and pincode fields. Since these kind of fields are part of address sub-file field, we can create an index on all of the fields of the sub-record. For making an index on all the 3 fields of the sub-document, use the following code. While the index is created, we can search for any of the sub-file fields utilising this index as follows

>db.Users.Locate("deal with.Town":"France")   
So the index created above would assist the following queries −
>db.Customers.Find("cope with.Metropolis":"France","deal with.Country":"Paris") 
It will look hyperlink query -
>db.Users.Discover("cope with.Town":"France","cope with.Country":"Paris",

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.