How to index data in MongoDB

Irrespective of what database you use, performance of any query depends on indexing of data fields in the database. MongoDB is no different.

By default MongoDB creates an index on field _id. But it is not very useful because you are not going to be querying data based on this field. Like any RDBMS like Microsoft SQL Server, you will be required to identify fields that you will need to use for indexing. For this discussion, I will use an example from my log aggregation application. I have an object that keeps tracks of user's authentication activity.

public class AuthActivityLog
        public string Username { get; set; }
        public DateTime ActivityOnUtc { get; set; }
        public int ActivityTypeId{get;set;}
        public AuthActivityType ActivityType
            get => (AuthActivityType)ActivityTypeId;
            set => ActivityTypeId = (int)value;
        public string Location { get; set; }
        public string Notes { get; set; }
        public string Device { get; set; }

When the application processes the data, it queries the records by ActivityOnUtc . If there is no index on this field, then every query will cause all documents to be scanned. That will degrade performance of the application. So, we are going to need put an index on this field.

How to add index to a field in MongoDB

You can use following steps to add index on a field. I will use example of adding index on ActivityOnUtc from my object.

  • Start mongo shell. You will install mongosh when installing MongoDB.
  • Run createIndex command on collection in the database.
use ByteMonitor

In above example, using -1 indicates that records will be indexed in descending order. A value of 1 indicates ordering of records in descending order.

If you want to verify that index has been added on the field, you can use getIndexes command to list all indexes on a collection. Following snippet shows the indexes on my collection and you can see that it does have an index on ActivityOnUtc field.


        "v" : 2,
        "key" : {
            "_id" : 1
        "name" : "_id_"
        "v" : 2,
        "key" : {
            "ActivityOnUtc" : -1
        "name" : "ActivityOnUtc_-1"

In this post, I have talked about adding a simple index on one field only. In subsequent posts, I will discuss more indexing on MongoDB collections and fields.




17.5 °C / 63.5 °F

weather conditions Clouds

Monthly Posts

Blog Tags