index / key: MongoDB


Lets look at some basics of indexes in MongoDB.

If we have 3 fields in a document – name, age, sex
We could make name or age or sex or (name, age) or (name, age, sex) as index.

index-key-mongodb

Assume that we make a index out of (name, age, sex)
In this case, we need to use the keys from left to right.

If we use “name” in our command, it makes use of the index.
If we use (“name”, “age”) in our command, it makes use of the index.
If we use (“name”, “age”, “sex”) in our command, it makes use of the index.

If we use “age” in our command, it can’t use the index for its operation.
If we use (“age”, “sex”) in our command, it can’t use the index for its operation.

If we use (“name”, “sex”) in our command, it simply uses “name” field and ignores “sex” field.

indexes / keys: MongoDB


[youtube https://www.youtube.com/watch?v=NiP-zX-jPaY]

YouTube Link: https://www.youtube.com/watch?v=NiP-zX-jPaY [Watch the Video In Full Screen.]



For convenience, mongoDB adds “_id” field to each document inserted. “_id” is unique across the collection. And index is automatically created on “_id”.

Since index information is stored in “system.indexes” collection – it consumes disk too. So we need to make sure to add indexes to only those fields which we access frequently. Also note that, each time a document is inserted, “system.indexes” collection must be updated with the new index information, which takes time, bandwidth and disk space. So we need to be careful while creating indexes.

Leave a Reply

Your email address will not be published. Required fields are marked *