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 the address subdocument and tags array.
Index array field
Suppose we retrieve users based on tags, for this we need to index the array tags in the collection.
To create an index in an array, you need to index each field in the array in turn. So when we create an index for the array tags, we will create separate indexes for the three values of 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 of the collection like this:
>db.users.find({tags:"cricket"})
To verify that we are using the index, we can use explain command:
>db.users.find({tags:"cricket"}).explain()
The execution result of the above command will display "cursor" : "BtreeCursor tags_1", which means that the index has been used.
Index sub-document fields
Suppose we need to retrieve documents through the city, state, and pincode fields. Since these fields are fields of sub-documents, we need to index the sub-documents. .
Create an index for the three fields of the subdocument, the command is as follows:
>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})
Once the index is created, we can use the fields of the subdocument to retrieve data:
>db.users.find({"address.city":"Los Angeles"})
Remember Query expressions must follow the order of the specified index. So the index created above will support the following query:
>db.users.find({"address.city":"Los Angeles","address.state":"California"})
Also supports the following query:
>db.users.find({"address.city":"LosAngeles","address.state":"California","address.pincode":"123"})