Hi @steevej , sorry for the delay for responding.
Here are more details with another example.
- I got a collection with 1.6M documents, each document having a field creationDate
- there is an index created on creationDate
Here is a simple pipeline for an aggregation, targetting documents created in the last 4 days :
[
{
$match: {
$expr: {
$gte: [
"$creation_date",
{
$subtract: ["$$NOW", 345600000]
}
]
}
}
},
{
$group: {
_id: {
creation_date: {
$dateToString: {
format: "%Y-%m-%d",
date: "$creation_date"
}
}
},
total: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
creation_date: "$_id.creation_date",
total: {
$toInt: "$total"
}
}
}
]
The index is not used :
But modifing the stage “$match” with an explicit date, like this
{
$match: {
$expr: {
$gte: [
"$creation_date",
ISODate("2024-05-24T17:11:00.000+00:00")
]
}
}
}
Index is well used