Docs Menu
Docs Home
/
MongoDB Manual
/ / /

cursor.hint()

On this page

  • Definition
  • Compatibility
  • Behavior
  • Examples
cursor.hint(index)

Important

mongosh Method

This page documents a mongosh method. This is not the documentation for a language-specific driver, such as Node.js.

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.

Call this method on a query to override MongoDB's default index selection and query optimization process. Use db.collection.getIndexes() to return the list of current indexes on a collection.

The cursor.hint() method has the following parameter:

Parameter
Type
Description

index

string or document

The index to "hint" or force MongoDB to use when performing the query. Specify the index either by the index name or by the index specification document.

You can also specify { $natural : 1 } to force the query to perform a forwards collection scan, or { $natural : -1 } for a reverse collection scan.

This method is available in deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

Note

This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.

  • When an index filter exists for the query shape, MongoDB ignores the hint().

  • If a query includes a $text expression, you cannot use hint() to specify which index to use for the query.

  • If you use hint() on a hidden index or an index that doesn't exist, the operation returns an error.

  • On a time series collections, you can only specify hints using the index name, not the index key pattern.

The following example returns all documents in the collection named users using the index on the age field.

db.users.find().hint( { age: 1 } )

You can also specify the index using the index name:

db.users.find().hint( "age_1" )

You can specify { $natural : 1 } to force the query to perform a forwards collection scan:

db.users.find().hint( { $natural : 1 } )

You can also specify { $natural : -1 } to force the query to perform a reverse collection scan:

db.users.find().hint( { $natural : -1 } )

Tip

See also:

Back

cursor.hasNext