Consider the following collections of documents (users):
{ "Address": { "City": "Los Angeles", "state" : "California" , "pincode" : " 123 " }, " tags ": [ "music" "cricket" , "blogs" Span class= "PLN" > ], "name" : "Tom benzamin" }
The above document contains the address subdocument and tags array.
Indexed array fields
Let's say we retrieve the user based on the tag, so we need to index the array tags in the collection.
When you create an index in an array, you need to index each of the fields in a sequence. So when we create an index for an array of tags, we establish separate indexes for music, cricket, blogs three values.
Use the following command to create an array index:
>db. Users. Ensureindex({"tags":1})
After the index is created, we can retrieve the tags field of the collection in this way:
>db. Users. Find({tags:"Cricket"})
To verify that we used the index, you can use the explain command:
>db. Users. Find({tags:"Cricket"}). Explain()
"Cursor": "Btreecursor tags_1" appears in the result of the above command execution, indicating that the index has been used.
Indexed sub-document fields
Suppose we need to retrieve the document through the city, state, pincode fields, because these fields are the fields of the subdocument, we need to index the subdocuments.
To create an index for the three fields of a 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 the data:
>db. Users. Find({"address.city":"Los Angeles"})
Remember that the query expression 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"})
The following queries are also supported:
>db. Users. Find({"address.city":"LosAngeles","Address.state":"California"," Address.pincode ":" 123 "})
MongoDB Advanced Index