cursor.hint()

Definition

  • cursor.hint(index)

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

Call this method on a query to override MongoDB’s default indexselection and query optimization process.Use db.collection.getIndexes() to return the list ofcurrent indexes on a collection.

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

ParameterTypeDescriptionindexstring or documentThe index to “hint” or force MongoDB to use when performing the query.Specify the index either by the index name or by the indexspecification document.

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

Behavior

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

You cannot use hint() if the query includesa $text query expression.

Examples

Specify an Index

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

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

You can also specify the index using the index name:

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

Force Collection Scans

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

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

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

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

See also