Hello @Alex_Bjorlig,
You will require at least three indexes to support the above five queries. Those would be single field indexes on fields color
, category
and size
respectively. These three indexes can support the five queries you had posted.
The second alternative is instead of the single field index on color
, you can create a compound index on one (or both) of these - color+category
and color+category+size
.
But, there are couple of things to consider:
- Indexes require disk space and when they are to used will be loaded in to the RAM memory - these are resources. More indexes and compound indexes can consume these resources and can affect the performance.
- Another aspect is that the most important queries should be considered when creating your indexes - all queries may not need indexes.
- Consider the indexing strategy of Selectivity before creating the compound indexes.
You will need some test data, create these indexes and try your queries. Then measure their usage and performance - for example, you can use explain
to generate the query plans and study them.
I don’t think you can run explain
on the countDocuments
method, but countDocuments - mechanics says that underlying this method is the aggregation query:
db.collection.aggregate([
{ $match: <query> },
{ $group: { _id: null, n: { $sum: 1 } } }
])
And, you can run explain on the aggregation query.