Do indexes work if only a prefix of query fields is indexed in MongoDB?

18 views Asked by At

I have a schema like this:

{
   name: string,
   age: number,
   marks: number
}

And I have a compound index on name and age fields.

{ name: 1, age: 1}

If I have a query like this:

collection.find({ name: 'X', age: 10, marks: 100 })

Will the indexes on name and age help mongo to optimise the query?

If I have a separate index on marks { marks: 1 }, will it work now?

Or do I need to have compound index on all three to make it work { name: 1, age: 1, marks: 1 } ?

1

There are 1 answers

1
Md Minhaz Ahamed On
  1. { name: 1, age: 1 } Index on name and age will narrow down the search documents first, but it will still need to scan through those matched documents to find the ones with marks equal to 100

  2. Separate { marks: 1 } Index on marks will narrow down the search documents first, but it will still need to scan through those matched documents to find the ones by filtering name and age

  3. { name: 1, age: 1, marks: 1 } This index can fully cover the query. MongoDB can efficiently use this index to filter based on all three fields: name, age, and marks. It will not require a collection scan

So to answer your question, you need compound indexing on all three. I hope this covers your concern