Query Plans

The MongoDB query optimizer processes queries and chooses the most efficient query plan for a query given the available indexes. The query system then uses this query plan each time the query runs. The query optimizer occasionally reevaluates query plans as the content of the collection changes to ensure optimal query plans.

You can use the explain() method to view statistics about the query plan for a given query. This information can help as you develop indexing strategies.

Query Optimization

To create a new query plan, the query optimizer:

  1. runs the query against several candidate indexes in parallel.

  2. records the matches in a common results buffer or buffers.

    If an index returns a result already returned by another index, the optimizer skips the duplicate match. In the case of the two buffers, both buffers are de-duped.

  3. stops the testing of candidate plans and selects an index when one of the following events occur:

    • An unordered query plan has returned all the matching results; or
    • An ordered query plan has returned all the matching results; or
    • An ordered query plan has returned a threshold number of matching results:
      • Version 2.0: Threshold is the query batch size. The default batch size is 101.
      • Version 2.2: Threshold is 101.

The selected index becomes the index specified in the query plan; future iterations of this query or queries with the same query pattern will use this index. Query pattern refers to query select conditions that differ only in the values, as in the following two queries with the same query pattern:

db.inventory.find( { type: 'food' } )
db.inventory.find( { type: 'utensil' } )

Query Plan Revision

As collections change over time, the query optimizer deletes the query plan and re-evaluates after any of the following events:

  • The collection receives 1,000 write operations.
  • The reIndex rebuilds the index.
  • You add or drop an index.
  • The mongod process restarts.
  • You run a query with explain().