Covered Queries and Indexes in MongoDB

Covered Queries and Indexes in MongoDB

A covered query is a query that can be satisfied entirely using an index and does not have to examine any documents. Covered query is When the query criteria and the projection of a query include only the indexed fields, MongoDB returns results directly from the index without scanning any documents or bringing documents into memory. These covered queries can be very efficient. An index covers a query when all of the following apply:

  • All the field in the query are in the index
  • All the projected field are part of the same index
  • No field in the query are equal to null

Using Covered Queries

Inserting data

To test covered queries, we'll insert some dummy data into our collection.

db.articles.insert([
{author: "yamicode", name: "article 1", date: new Date("02/12/207"), views: 10},
{author: "yamicode", name: "article 2", date: new Date("02/12/207"), views: 5},
{author: "jhon", name: "article 3", date: new Date("02/12/207"), views: 12},
])

Creating our index data

For example, our collection articles has the following index on the name and author fields:

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

Using covered query

This index will cover the following operation which queries on the name and author fields and returns only the name field:

db.articles.find(
   { author: "yamicode", name: "article 1" },
   { name: 1, _id: 0 }
)

Explaining the result

db.articles.explain().find(
   { author: "yamicode", name: "article 1" },
   { name: 1, _id: 0 }
)

result

{
	...
	"stage" : "PROJECTION_COVERED"
	...
}

Restrictions on Indexed Fields:

  • Geospatial indexes cannot cover a query.
  • Multikey indexes cannot cover queries over array field(s).