I am trying to aggregate in MongoDB.
I have a collection with some items. Each item has an array rows and each object in rows has fields quantity and price.
I want to multiply quantity and price, but I don't know how to specify the fields correctly.
I have tried
const pipeline = [
{
$group: {
_id: {
number: '$number',
},
total: {
$sum: {
$multiply: [
'$rows.quantity',
'$rows.price'
]
}
},
}
}
];
but it says that $multiply only supports numeric types and not arrays.
So it seems it doesn't understand that $rows.quantity is the numeric type field quantity in each object in the array.
I guess I should probably use $each or something else in order to iterate through the objects in the array.
From Using multiply aggregation with MongoDB I see that I am specifying the fields correctly; however, in that example it is a nested object instead of an array, so maybe I have to use https://docs.mongodb.org/v3.0/reference/operator/aggregation/unwind/?
Sample document
{
number: 2,
rows: [
{
quantity: 10,
price: 312
},
{
quantity: 10,
price: 312
},
{
quantity: 10,
price: 312
},
]
}