As shown below, documents in the collection look like this.
The aggregation I need should count the number of devices monthly, the device should start being counted from the first month it appears, and from that month until the current month, independent of whether or not it appears again.
[
{
"device": 1,
"date": ISODate("2022-7-10")
},
{
"device": 2,
"date": ISODate("2022-8-10")
},
{
"device": 1,
"date": ISODate("2022-9-11")
},
{
"device": 3,
"date": ISODate("2022-10-11")
}
]
The output would be:
[
{
"_id": {
year: 2022,
month: 7
},
count: 1 // device 1
},
{
"_id": {
year: 2022,
month: 8
},
count: 2 // device 1 and 2
},
{
"_id": {
year: 2022,
month: 9
},
count: 2 // device 1 and 2
},
{
"_id": {
year: 2022,
month: 10
},
count: 3 // device 1, 2 and 3
}
]