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.

CategoryCursor
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.find(<filter>).hint(<indexKeyOrName>)

⚙️ Parameters

index key or nameThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏