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 documents contain the address subdocument and the tags array.
Index Array Fields
Suppose we want to retrieve users based on tags; for this we need to create an index on the tags array in the collection.
Creating an index on an array requires indexing each field in the array in turn. So when we create an index on the tags array, separate indexes are created for the three 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 query the tags field of the collection like this:
>db.users.find({tags:"cricket"})
To verify that the index was used, we can use the explain command:
>db.users.find({tags:"cricket"}).explain()
If the result of the above command shows "cursor" : "BtreeCursor tags_1", it means the index was used.
Index Subdocument Fields
Suppose we need to retrieve documents by the city, state, and pincode fields; since these fields are fields of a subdocument, we need to create an index on the subdocument.
The command to create an index on the three fields of the subdocument is as follows:
>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})
Once the index is created, we can use the subdocument's fields to retrieve data:
>db.users.find({"address.city":"Los Angeles"})
Query expressions do not necessarily follow the specified index order; mongodb optimizes automatically. So the index created above will support the following queries:
>db.users.find({"address.state":"California","address.city":"Los Angeles"})
The following queries are also supported:
>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})