Consider the following collection of documents (users):
{
"address": {
"city": "Los Angeles",
"state": "California",
"pincode": "123"
},
"tags": [
"music",
"cricket",
"blogs"
],
"name": "Tom Benzamin"
}
The above document contains Suppose we retrieve users based on tags, for which 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 index the array tags, we create separate indexes for the values music, cricket, and blogs. Create an array index using the following command: After creating the index, we can retrieve the tags field of the collection as follows: To verify that we used the index, we can use the explain command: If “cursor”: “BtreeCursor tags_1” is displayed in the execution result of the above command, the index has been used. Suppose we need to retrieve the document through the city, state, and pincode fields, and since these fields are the fields of the subdocument, we need to index the subdocument. Create an index for the three fields of the subdocument, with the following command: Once the index is created, we can use the fields of the subdocument to retrieve the data: The query expression does not necessarily follow the order of the specified index, and mongodb optimizes automatically. So the index created above will support the following query: The following queries are also supported:
address
Subdocuments and
tags
Array. 3.36.1. Index array field ¶
>db.users.ensureIndex({"tags":1})
>db.users.find({tags:"cricket"})
>db.users.find({tags:"cricket"}).explain()
3.36.2. Index subdocument field ¶
>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})
>db.users.find({"address.city":"Los Angeles"})
>db.users.find({"address.state":"California","address.city":"Los Angeles"})
>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})