Indexes in MongoDB

Indexes in MongoDB

Indexes in MongoDB are features that are used to retrieve data more efficiently and more quickly. Indexes can speed up our find, update or delete queries. The end-user can not see the indexes, they are just used to speed up search/queries.

In general an index is an ordered list of all the values of a particular field inside a collection. Every index has a pointer to the full document that it belongs to.

MongoDb ordered list indexes schema explained with examples

Create indexes in MongoDB

To create an index we use the createIndex method. This method takes an object as argument which has as keys the name of the fields and as a value the order of those keys either ascending or descending (1 or -1)

db.articles.createIndex({"author": 1})

Result of createIndex

{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

In the result you get a number of indexes of 2 because MongoDB already have one default index which is the _id field.

See the impact of indexes in MongoDB collections

In general to see the difference between using indexes and before using them you can use the method explain("executionStats") which will give you statistiques about the execution time, the method chosen (Collection scan or Indexes scan) and the number of document processed to return the result. Use some big collection that contains a lot of documents to see some real changes because in small collection it's quick in both ways.

Using explain to analyse our queries before and after using indexes in MongoDB

db.articles.explain("executionStats").find({author: "Yami Code"})

Example of Result with Indexes Scan

{...,
	"executionStats" : {
                "executionTimeMillis" : ...,
                "totalDocsExamined" : ...,
                "totalKeysExamined" : ...,
                ...,
                "executionStages":{
                	"inputStage" : {
                		"stage" : "IXSCAN"
                	}
            	}
    }
}

Lising our indexes in MongoDB

db.articles.getIndexes()

Drop an index in MongoDB

db.articles.dropIndex({"author": 1})

Don't use too many indexes because it can slow down your update,insert and delete queries because in those operations MongoDB have to update all the ordered lists of indexes.

Compound indexes in MongoDB

A compound index in MongoDB is an index that are contained from multiple fields.

Usage of compound indexes in MongoDB

db.articles.createIndex({"author": 1, "type": 1})

The order of fields in create compound index is important. For example when looking only for field author MongoDB can use this index to speed up your query because it's sorted in the coumpound index.

More about indexes

To find more about indexes we provide you with some links to know more: