This version of the documentation is archived and no longer supported.

Limit the Number of Entries Scanned

This tutorial describes how to limit the text search to scan only those documents with a field value.

The text command includes the filter option to further restrict the results of a text search. For a filter that specifies equality conditions, this tutorial demonstrates how to perform text searches on only those documents that match the filter conditions, as opposed to performing a text search first on all the documents and then matching on the filter condition.

Consider a collection inventory that contains the following documents:

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

A common use case is to perform text searches by individual departments, such as:

db.inventory.runCommand( "text", {
                                   search: "green",
                                   filter: { dept : "kitchen" }

To limit the text search to scan only those documents within a specific dept, create a compound index that specifies an ascending/descending index key on the field dept and a text index key on the field description:

                            dept: 1,
                            description: "text"


  • The ascending/descending index keys must be listed before, or prefix, the text index keys.
  • By prefixing the text index fields with ascending/descending index fields, MongoDB will only index documents that have the prefix fields.
  • You cannot include multi-key index fields or geospatial index fields.
  • The text command must include the filter option that specifies an equality condition for the prefix fields.

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

db.inventory.runCommand( "text", {
                                   search: "green",
                                   filter: { dept : "kitchen" }

The returned result includes the statistics that shows that the command scanned 1 document, as indicated by the nscanned field:


  "queryDebugString" : "green||||||",
  "language" : "english",
  "results" : [
                  "score" : 0.75,
                  "obj" : {
                            "_id" : 3,
                            "dept" : "kitchen",
                            "description" : "a green placemat"
  "stats" : {
              "nscanned" : 1,
              "nscannedObjects" : 0,
              "n" : 1,
              "nfound" : 1,
              "timeMicros" : 211
  "ok" : 1

For more information on the result set, see Output.