Index on timestamp fields

Please share the explain plan of your slow queries.

Please share the exact indexes with getIndexes().

Please share sample documents that match your slow queries.

Please share size information about your collections and databases.

Code that is not indented is hard to read. Time is scarce and most will not take the time to indent someone else code. I won’t.

The are other date functions such as $dateToParts or $dateTrunc that may be more efficient than $dateToString that must interpret a format string for each document.

I do not understand the purpose of

since you are counting. I suspect it is useless and potentially detrimental since the index does not include that field.