Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

cursor.hint()

On this page

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

Important

mongosh Method

This is a mongosh method. This is not the documentation for Node.js or other programming language specific driver methods.

In most cases, mongosh methods work the same way as the legacy mongo shell methods. However, some legacy methods are unavailable in mongosh.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

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.

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

←  cursor.hasNext()cursor.isExhausted() →