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 } ?
{ name: 1, age: 1 }Index onname and agewill 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 100Separate
{ marks: 1 }Index onmarkswill 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{ 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 scanSo to answer your question, you need compound indexing on all three. I hope this covers your concern