Sharing because this cost me a deploy and the reason is easy to miss.
Setup: a collection with about 500k documents, 20 GB, growing 10 GB a month. One endpoint polls it all day: newest unclaimed request for a tenant. The query looked like this:
{ tenant, namespace, status: "New", "spec.curl": { $exists: true, $ne: "" } }
It had slowed to about 12 seconds.
Most documents in the collection are finished, so a normal index would mostly hold entries that never match. A partial index only indexes documents that match a condition, so I built one:
db.requests.createIndex(
{ tenant: 1, namespace: 1, status: 1 },
{ partialFilterExpression: { "spec.curl": { $gt: "" }, status: "New" } }
)
That covers a few thousand documents instead of 500k. Deployed it. Query still took 12 seconds.
`explain()` showed a COLLSCAN, so the index was not being used. The reason: MongoDB only uses a partial index when it can tell the query is a subset of the index condition. My query said `$exists: true, $ne: ""`. The index said `$gt: ""`. For string fields those match the same documents, but the planner does not reason that far. It wants the query to use a predicate it can match directly.
I changed the query to `"spec.curl": { $gt: "" }`. The index got used. 11 ms.
Second gotcha from the same week. Our app creates its indexes on startup and exits if an index with the same name exists with different options. One environment had an older version of this index (same name, partial filter was only `status: "New"`). The app crash-looped on deploy until that index was dropped. New rule for us: build the index in Atlas first with a rolling build, same name and options, wait for it to finish, then ship the code.
What I'd pass on:
- Write the query the same way as the partial filter. Same meaning is not enough.
- Run `explain("executionStats")` on the real query before you say the index is done.
- Partial indexes fit any "small active subset inside a big collection" pattern. Most queue-style collections are like that.
Does anyone have a check that catches "query does not match the partial filter" before deploy? Right now I catch it by reading the code.