DEV Community

Cover image for 10 Best Practices While Using MongoDB Indexes
Shreetesh M
Shreetesh M

Posted on

10 Best Practices While Using MongoDB Indexes

Introduction

Here are some points on optimization and best practices while using MongoDB indexes to ensure good performance of queries in deployment.

Note
What are indexes? Check out this page.

The below points will generally work for most applications.

Best Practices

Always index each of your collections, it makes a huge difference in query performance.

  1. Use the ESR (Equality, Sort, Range) rule while building compound indexes. These almost always support index scans for both query predicate and sorting.

  2. Use partial indexes at the first opportunity available in your application. They can reduce the size of your index.

  3. Remove indexes that are already prefixes of a compound index. For example, if a compound index such as:

    {stock: 1, date: -1, price: 1}
    

    is available, then its valid prefixes:

    {stock: 1, date: -1}
    {stock: -1, date: 1}
    {stock: 1}
    {stock: -1}
    

    need not be separately created as indexes. The first compound index can serve the same functionality as these indexes.

  4. Build compound indexes such that most of your queries are covered using a projection. This will prevent the need to fetch documents entirely and will reduce query time.

  5. Avoid using unrooted or right-anchored regex in the query field. This kind of regex will increase query time due to the variability in the beginning of the value, even if an index is present for that field.
    Some examples of unrooted expressions:

    /hello/
    /.world/
    /.*manufacturer$/
    
  6. Limit to 50 indexes per collection as a thumb rule. Remember that even indexes will reside in the memory, thus reducing the size of your working set. Having a lot of indexes will also degrade the database write performance.

  7. Before deleting an index, hide the index to check the performance impact of deleting the index. Hidden indexes will continue to be updated like normal indexes, but will not be used by MongoDB.
    To hide an index:

    db.collection.hideIndex("my_index_1")
    
  8. Use $indexStats to check how well and how frequently an index is being used by MongoDB.

    db.collection.indexStats({index: "my_index_1"})
    
  9. Use wildcard indexes when you cannot know the schema in advance. Do not ignore indexing in such cases. In other words, use them when fields in a document can have arbitrary names that are decided at runtime.

  10. Prefer using compound indexes over relying on index intersection.

Note

All the above points are compiled from the documentation and official MongoDB sources.

Cover image credits: EDUCBA.

Top comments (0)