May 17, 2021 MongoDB
Consider the following collection of documents (users):
{ "address": { "city": "Los Angeles", "state": "California", "pincode": "123" }, "tags": [ "music", "cricket", "blogs" ], "name": "Tom Benzamin" }
The above documentation contains address sub-documents and tags arrays.
Suppose we retrieve users based on labels, 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 create an index for the array tags, a separate index is created for the three values of music, cricket, and blogs.
Use the following commands to create an array index:
>db.users.ensureIndex({"tags":1})
After we create the index, we can retrieve the tags field of the collection like this:
>db.users.find({tags:"cricket"})
To verify that we are using indexes, we can use the explain command:
>db.users.find({tags:"cricket"}).explain()
The above command execution results show "cursor": "BtreeCursor tags_1" to indicate that the index has been used.
Suppose we need to retrieve documents through city, state, pincode fields, and since these fields are fields for sub-documents, we need to index sub-documents.
Create an index for the three fields of the sub-document, and the commands are 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 sub-document to retrieve the data:
>db.users.find({"address.city":"Los Angeles"})
Remember that query expressions must follow the order of the specified indexes. S o the index created above will support the following queries:
>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"})