Limit the Number of Entries Scanned

This tutorial describes how to create indexes to limit the number ofindex entries scanned for queries that includes a $textexpression and equality conditions.

A collection inventory contains the following documents:

  1. { _id: 1, dept: "tech", description: "lime green computer" }
  2. { _id: 2, dept: "tech", description: "wireless red mouse" }
  3. { _id: 3, dept: "kitchen", description: "green placemat" }
  4. { _id: 4, dept: "kitchen", description: "red peeler" }
  5. { _id: 5, dept: "food", description: "green apple" }
  6. { _id: 6, dept: "food", description: "red potato" }

Consider the common use case that performs text searches byindividual departments, such as:

  1. db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )

To limit the text search to scan only those documents within a specificdept, create a compound index that first specifies anascending/descending index key on the field dept and then atext index key on the field description:

  1. db.inventory.createIndex(
  2. {
  3. dept: 1,
  4. description: "text"
  5. }
  6. )

Then, the text search within a particular departmentwill limit the scan of indexed documents. For example, the followingquery scans only those documents with dept equal to kitchen:

  1. db.inventory.find( { dept: "kitchen", $text: { $search: "green" } } )

Note

  • A compound text index cannot include any other special indextypes, such as multi-key orgeospatial index fields.
  • If the compound text index includes keys preceding thetext index key, to perform a $text search, the querypredicate must include equality match conditions on the precedingkeys.
  • When creating a compound text index, all text index keys mustbe listed adjacently in the index specification document.

See also

Text Indexes