Latest web development tutorials

MongoDB advanced indexing

Consider the following document collections (users):

{
   "address": {
      "city": "Los Angeles",
      "state": "California",
      "pincode": "123"
   },
   "tags": [
      "music",
      "cricket",
      "blogs"
   ],
   "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:

>db.users.ensureIndex({"tags":1})

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

>db.users.find({tags:"cricket"})

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

>db.users.find({tags:"cricket"}).explain()

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:

>db.users.ensureIndex({"address.city":1,"address.state":1,"address.pincode":1})

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

>db.users.find({"address.city":"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({"address.city":"Los Angeles","address.state":"California"}) 

Also supports the following query:

>db.users.find({"address.city":"LosAngeles","address.state":"California","address.pincode":"123"})