Easy Tutorial
❮ Mongodb Analyzing Queries Mongodb Linux Install ❯

MongoDB Advanced Indexes

Consider the following document collection (users):

{
   "address": {
      "city": "Los Angeles",
      "state": "California",
      "pincode": "123"
   },
   "tags": [
      "music",
      "cricket",
      "blogs"
   ],
   "name": "Tom Benzamin"
}

The above document contains an address sub-document and a tags array.


Indexing Array Fields

Suppose we need to retrieve users based on tags, for this we need to create an index on the tags array in the collection.

When creating an index on an array, an index is created for each field in the array. So when we create an index on the tags array, separate indexes are created for the values music, cricket, and blogs.

Use the following command to create an array index:

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

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

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

To verify that the index is being used, you can use the explain command:

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

The result of the above command will show "cursor" : "BtreeCursor tags_1", indicating that the index is being used.


Indexing Sub-document Fields

Suppose we need to retrieve documents based on the city, state, and pincode fields, since these fields are part of a sub-document, we need to create an index on the sub-document.

To create an index on the three fields of the sub-document, use the following command:

>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 data:

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

The query expression does not necessarily follow the specified index order; MongoDB automatically optimizes it. Therefore, the index created above will support the following query:

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

It also supports the following query:

>db.users.find({"address.city":"Los Angeles","address.state":"California","address.pincode":"123"})
❮ Mongodb Analyzing Queries Mongodb Linux Install ❯