Mongodb Advanced Indexing
# MongoDB Advanced Indexing
Consider the following document collection (users):
{ "address": { "city": "Los Angeles", "state": "California", "pincode": "123" }, "tags": [ "music", "cricket", "blogs" ], "name": "Tom Benzamin"}
The above document contains an address subdocument and a tags array.
* * *
## Indexing Array Fields
Suppose we want to retrieve users based on their tags. To do this, we need to create an index on the tags array in the collection.
To create an index on an array, we need to create an index for each element in the array. So, when we create an index for the tags array, it will create separate indexes for the values "music", "cricket", and "blogs".
Use the following command to create an array index:
>db.users.ensureIndex({"tags":1})
After creating the index, we can retrieve the tags field from the collection like this:
>db.users.find({tags:"cricket"})
To verify that we are using the index, we can use the explain command:
>db.users.find({tags:"cricket"}).explain()
The result of the above command will show "cursor" : "BtreeCursor tags_1", which indicates that the index is being used.
* * *
## Indexing Subdocument Fields
Suppose we need to retrieve documents based on the city, state, and pincode fields. Since these fields are part of a subdocument, we need to create an index on the subdocument.
To create an index on the three fields of the subdocument, use the following command:
>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})
Once the index is created, we can use the subdocument fields to retrieve data:
>db.users.find({"address.city":"Los Angeles"})
The query expression does not necessarily have to follow the order of the specified index; MongoDB will optimize it automatically. So, the index created above will support the following query:
>db.users.find({"address.state":"California","address.city":"Los Angeles"})
It also supports the following query:
>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})
[](#)(#)
(#)[](#)
YouTip