Doctrine ODM allows to group a set of matched documents: https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.9/reference/aggregation-stage-reference.html#group
Consider documents having properties “type” and “date”. I’d like to get data grouped by type and sub-grouped by month and year.
So far, I was able to group like the following:
array(2) {
["_id"]=>
array(1) {
["type"]=>
string(6) "A"
}
["byMonth"]=>
array(5) {
[0]=>
array(2) {
["month"]=>
int(7)
["year"]=>
int(2025)
}
[1]=>
array(2) {
["month"]=>
int(7)
["year"]=>
int(2025)
}
[2]=>
array(2) {
["month"]=>
int(3)
["year"]=>
int(2025)
}
[3]=>
array(2) {
["month"]=>
int(3)
["year"]=>
int(2025)
}
[4]=>
array(2) {
["month"]=>
int(1)
["year"]=>
int(2025)
}
}
}
array(2) {
["_id"]=>
array(1) {
["type"]=>
string(6) "B"
}
["byMonth"]=>
array(1) {
[0]=>
array(2) {
["month"]=>
int(2)
["year"]=>
int(2025)
}
}
}
Here is the code used:
$aggBuilder = $dm->createAggregationBuilder(Example::class);
$aggBuilder->match()
->field('date')
->gte($from)
->lte($to)
;
$aggBuilder->group()
->field('id')
->expression(
$aggBuilder->expr()
->field('type')
->expression('$type')
)
->field('byMonth')
->push(
$aggBuilder->expr()
->field('month')
->month('$date')
->field('year')
->year('$date')
)
;
But as you can see, data is not aggregated for type A on months 3 and 7.
So, instead of just pushing the data (hence not grouped by month), how is it possible to aggregate the nested data by month?