WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

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": [
        "travel",
        "cook",
        "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

>db.users.ensureIndex({"tags":1})
After creating the index, we can search on the tags field of the collection like this −
>db.users.find({tags:"cook"})

To verify that proper indexing is used, use the following explain command
>db.users.find({tags:"cook"}).explain()

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

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

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

>db.users.find({"address.city":"France"})   
So the index created above would support the following queries −
>db.users.find({"address.city":"France","address.state":"Paris"}) 
It will look link query -
>db.users.find({"address.city":"France","address.state":"Paris",
   "address.pincode":"75008"})




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.