Search code examples
mongodbmongoose

In MongoDB is there a performance difference when including indexes and non-indexed values in a filter?


If we have a model like

{
  typeIndex: number
  value: string
}

Are either of these more performant than the other?

const docs1 = await Model.find({ typeIndex: 1, value: regexpstring })
const docs2 = await Model.aggregate([
  { $match: { typeIndex: 1 } },
  { $match: { value: regexpstring} }
])

My hunch is to use the first one. Will it actually scan only indexes first and then the value, or because it sees value it will immediately go to document scanning?


Solution

  • The MongoDB query planner will combine the two match stages into one, so those queries are equivalent.

    If there is an index on typeIndex, it will be used in both cases. If that index also includes value the index can support that predicate if the regular expression is anchored to the beginning of the string.