Latest web development tutorials

MongoDB advanced indexing

Consider the following document collections (users):

   "address": {
      "city": "Los Angeles",
      "state": "California",
      "pincode": "123"
   "tags": [
   "name": "Tom Benzamin"

The above document contains sub-documents, and address an array of tags.

Indexed array field

Suppose we retrieve user-based label, for which we need to index the collection array tags.

Create an index in the array, the array of needs for each field in turn indexed. So when we create an index for the array tags, it will provide music, cricket, blogs three values ​​to establish a separate index.

Create an array index, use the following command:


After creating the index, we can retrieve the tags field collection:


We used to verify the use of the index, you can use the explain command:


The results of the above command will show "cursor": "BtreeCursor tags_1", it said the index has been used.

Index sub-document field

Suppose we need city, state, pincode field to retrieve documents, as these fields are fields subdocument, so we need a subdocument indexing.

Create an index for the three sub-fields of the document, the command is as follows:


Once the index is created, we can use the field to retrieve the data sub-documents:

>db.users.find({"":"Los Angeles"})   

Remember query expression must follow the order of the specified index. So the index created above will support the following query:

>db.users.find({"":"Los Angeles","address.state":"California"}) 

Also supports the following query: