Been looking for a solution for a while now but no luck, i have a database with 400k documents and i’m looking to make a query to retrieve result for a specific day of every year.
So for example every document with date 27 oct and it should return a document for 2022, 2021, 2020…
I am worry that a $match with $dateToParts to get day and month from the stored document’s date field would not be able to leverage an index on the date field.
It is not really an issue if this is a infrequent use-case. But what if it is.
One solution could be to use $in with a list of calculated exact dates. The caveat is that you need to limit the years so that the array of date is limited. Using Oct-27, the query, assuming data starts in 2017, could be
I think the chances for an IXSCAN are higher. But I could be wrong.
An alternative I see is to update the collection with the $dateToParts result and have an index on month:1,day:1,year:1. I include year:1 in the index so we can sort by year using the index.
The best solution at first is the simplest and it is the one provided by @Pavel_Duchovny.
Any optimization, like the ones I mentioned, should not be implemented unless you have performance problems. Do not make your code or data more complex before you need to.