Indexing Design Fundamentals / Testing Indexes with Explain()

Using an Explain Plan


Below is the code used to run the explain() method with mongosh to return an explain plan. An explain plan is a report that gives us information about possible plans for executing a query, including the winning plan that MongoDB selects.


Code

explain() Method

Use the explain() method, chained with the find() method to return the explain plan in mongosh.

db.collection.explain().find()


Query 1

This query is used to retrieve documents from the messages collection for a specific user, identified by userId, where the document timestamps fall within a specified date range. The results are sorted in descending order based on the timestamp field.

The explain() method is chained to this query with verbosity level set to executionStats. This will return an explain plan document in the terminal that will include execution stats for the winning plan.

db.messages.explain("executionStats").find(
  {
    userId: "user505", 
    timestamp: { 
     $gte: new Date("..."),      
     $lte: new Date("...") 
    } 
  }
).sort({ timestamp: -1 }) 


Query 2

This query is used to find all messages for a user within a time range and sort those messages by category.

The explain() method is chained to this query with verbosity level set to executionStats. This will return an explain plan document in the terminal that will include execution stats for the winning plan.

db.messages.explain("executionStats").find(
  {
    userId: "user505", 
    timestamp: { 
     $gte: new Date("..."),      
     $lte: new Date("...") 
    } 
  }
).sort({ category: 1 }) 


Query 3

This query filters documents by userId and isRead fields and is used to track which messages have been read by a user.

The explain() method is chained to this query with verbosity level set to executionStats. This will return an explain plan document in the terminal that will include execution stats for the winning plan.

db.messages.explain(“executionStats”).find(
  { 
    userId: "user505", 
    isRead: false 
  }
)