Grouping by multiple fields with the aggregation builder (question)
speedytwenty opened this issue · 2 comments
speedytwenty commented
I'm trying to determine the syntax for grouping by multiple fields using the aggregation builder.
Like this example from https://docs.mongodb.com/manual/reference/operator/aggregation/group/
db.sales.aggregate(
[
{
$group : {
_id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
]
)
I can elaborate on the question if needed but hoping I'm just missing something simple.
Eg.
How do I do this:
_id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
With this:
$aggregationBuilder->group()->field('_id')->????
Thanks in advanced for the help guys!
alcaeus commented
You have to create a nested expr object to be used with the field:
$builder
->group()
->field('_id')
->expression(
$builder
->expr()
->field('month')
->month('$date')
->field('day')
->dayOfMonth('$date')
->field('year')
->year('$date')
)
->field('totalPrice')
->sum(
$builder
->expr()
->multiply('$price', '$quantity')
)
->field('averageQuantity')
->avg('$quantity')
->field('count')
->sum(1);
speedytwenty commented
Awesome. This was exactly what I was looking for. Thanks Andreas!