hint() (Force an Index)
Last updated: 2026-10-09
hint() (Force an Index)
hint() forces a query to use a specific index: `db.users.find({ age: { $gt: 20 } }).hint({ age: 1 })`, passing either the index key or its name. The optimizer usually picks well, but hint() can override bad choices when data distribution is skewed. Use it sparingly in production and re-verify the index stays relevant.
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.find(<filter>).hint(<indexKeyOrName>)
⚙️ Parameters
| index key or name | The index to force, e.g. {age: 1} or 'age_1'. |
|---|
Returns:The cursor with the index forced (chainable).
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// hint: force the age_1 index
const result = db.users.find({ age: { $gt: 20 } })
.hint({ age: 1 })
.toArray()
result.length
Output:
35
📌 Notes
- An error is thrown when the hinted index does not exist
- hint() is not forever-optimal; re-evaluate as data changes
- hint({$natural: 1}) forces a collection scan
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow does hint relate to indexes?
Ahint() forces a query onto a given index, bypassing the optimizer's choice — a fix when the optimizer picks wrong.
QWhat if the hinted index does not exist?
AThe query errors immediately — it does not fall back to another index.
QHow do I force a collection scan with hint?
APass hint({$natural: 1}), which scans documents in physical order.