When would you attach hint() to a MongoDB query instead of letting the planner choose?
answer
- It narrows the planner's choices to one
- There is a form that forbids every index
- Best used while measuring, not in production
- Naming a missing one is an error, not a fallback
basics
~20 sMainly as a diagnostic: hint() forces the planner to consider only the index you name, so you can compare plans with explain. hint({$natural: 1}) forces a collection scan. Pinning an index permanently in application code freezes a decision that data changes will invalidate.
solid answer
~50 s`hint()` restricts the query planner to the index you name — by key pattern, `hint({ status: 1, createdAt: -1 })`, or by name, `hint("status_1_createdAt_-1")` — and `hint({ $natural: 1 })` forces a collection scan instead. Its everyday use is **measurement**: run `explain("executionStats")` with and without the hint and compare `totalKeysExamined`, `totalDocsExamined` and `nReturned` to prove which index is actually better before you create, drop or reorder anything. Pinning it in production code is a last resort — for example when the planner keeps flip-flopping between two plans of similar score and one has a catastrophic worst case. The cost is that the hint freezes today's decision: as the data distribution shifts or a better index appears, the query cannot adapt, and if the hinted index is ever dropped the query fails rather than degrading. Prefer fixing the index so the planner chooses correctly on its own.
code
javascript · 6 lines// compare candidates on the same query
const q = { status: "ACTIVE", createdAt: { $gt: cutoff } };
db.orders.find(q).explain("executionStats"); // planner's pick
db.orders.find(q).hint({ status: 1, createdAt: 1 }).explain("executionStats");
db.orders.find(q).hint({ $natural: 1 }).explain("executionStats"); // scan baselinego deeper
Know that hint() tells MongoDB which index to use for a query and that the planner otherwise chooses on its own. You are unlikely to be asked more than that here.
Explain the accepted forms — key pattern, index name, and $natural for a forced collection scan — and that hinting a missing index raises an error rather than falling back.
Demonstrate the tuning workflow: hint each candidate index, compare explain counters, and argue why the durable fix is the right index rather than a pinned plan.
Own the policy: whether hints are allowed in shipped code at all, what justification and review date a pinned plan carries, and how index names become part of a deployment contract once code depends on them.
## What hint() actually does By default MongoDB's planner enumerates candidate plans for a query shape, runs them side by side for a short trial, scores them by measured productivity, keeps the winner and caches it. `hint()` short-circuits that: it tells the server to consider only the named index (or, with `$natural`, no index at all). The query still returns correct results — a hint changes the access path, never the semantics. Accepted forms: by key pattern, `db.orders.find(q).hint({ status: 1, createdAt: -1 })`; by index name, `db.orders.find(q).hint("status_1_createdAt_-1")`; and `db.orders.find(q).hint({ $natural: 1 })` to force a collection scan. If you name an index that does not exist, the command **errors** — it does not silently fall back. That failure mode is one of the strongest arguments against sprinkling hints through application code: dropping an index becomes a breaking change instead of a performance change. Hints are not limited to `find`: `update`, `delete` and `findAndModify` accept a hint too, which matters when a bulk update picks a poor path. ## The legitimate use: measurement The honest answer to this interview question is that `hint()` is mostly a *tool for the person tuning the query*, not a production setting. The workflow: 1. Run `explain("executionStats")` normally. Record `nReturned`, `totalKeysExamined`, `totalDocsExamined`, `executionTimeMillis`, and which index won. 2. Re-run with `.hint(candidateIndex)` for each plausible index. Same counters. 3. Compare. If a candidate examines dramatically fewer keys, you have evidence for reordering or building an index — and evidence for *why*, not just a feeling. 4. `hint({ $natural: 1 })` gives you the baseline: what a plain collection scan costs. Sometimes the scan is close enough that the index is not worth its write cost. This is also how you validate a new index before dropping the old one, and how you demonstrate to a reviewer that a proposed index actually helps. ## When pinning is defensible A hint in shipped code is justified only with a stated reason and a review date. Real cases: - **Plan instability.** Two plans score similarly during the trial, so the winner flips depending on which documents the trial happened to touch, and one of them has a far worse tail latency. Pinning the safe one bounds the worst case. - **A query whose selectivity varies wildly by parameter**, where the plan chosen for one set of values is wrong for another. - **A maintenance or migration job** where you want a predictable scan or a predictable index walk, and predictability of runtime matters more than optimality. In every case the better first move is to fix the cause: build the index the query actually needs (equality fields first, then sort, then range), remove a redundant index that confuses the choice, or reshape the query. A hint treats the symptom. ## What pinning costs you - **It freezes a decision made against today's data.** Distributions shift; the index that was right at one million documents may be wrong at a hundred million. - **It blocks future improvement.** A better index added later will never be used by the hinted query, and nobody will notice. - **It couples code to index names.** Renaming or dropping an index breaks the query outright. - **It hides regressions.** The plan no longer changes, so the usual symptom that tells you the data changed — a plan flip — never fires. ## Related knobs, and what they are not Do not conflate `hint()` with clearing the plan cache. A cached plan can go stale, and the server re-evaluates a cached plan when it starts performing much worse than when it was cached; you can also clear cache entries administratively. That is a different lever from forcing an index and is usually the right one when the complaint is "it was fast until yesterday". Also note that a hint interacts with coverage and sorting: hinting an index that cannot supply the query's sort order will produce a blocking `SORT` stage that the planner might have avoided by choosing differently — another reason to always look at the hinted plan's explain output rather than assuming the hint helped. ## Answering well Lead with the diagnostic use, name `$natural` as the force-a-scan form, mention the hard error on a missing index, and close with the tradeoff — a hint is a decision you have to keep re-justifying, while a correct index keeps working on its own.
- What happens if you hint an index that does not exist on the collection?The operation fails with an error rather than falling back to the planner's own choice. That is why hints in application code are risky: dropping or renaming an index turns a tuning decision into an outage. If a hint must ship, treat the index it names as part of the code's contract and guard it in deployment checks.
- What does hint({$natural: 1}) do, and why would you use it?It forces a collection scan by telling the planner to use no index. Its main use is establishing a baseline while tuning — comparing explain counters for the scan against each candidate index shows whether an index is worth its write cost at all. It is occasionally used for maintenance jobs that will read most of the collection anyway.
- A query's plan started flipping between two indexes overnight. Is a hint the right fix?Usually not as the first move. A flip means the two plans score similarly during the planner's trial, so the real questions are whether the data distribution changed, whether one index is redundant, and whether the right compound index exists at all. Build or reorder that index so one plan wins clearly. Pin only if you must bound a bad tail latency, and record why.
saying these in an interview costs you the question
- Ships hint() in application code as a routine tuning step
- Thinks hint() can force an index that does not exist
- Believes hint() makes a query faster by definition
- Uses a hint instead of investigating why the plan changed
- Assumes hint({$natural: 1}) sorts results in insertion order