I have a list of items, and I want mongoDB return the result of the sum of their price*quantity, in other words, the total value of my items.
Schema = {
_id: ObjectId,
price: Number,
quantity: Number
}
I'm trying using the aggregation framework, or map reduce, but I can't figure out how correctly use it.
Here an there is an example for finding the sum of prices,
db.items.aggregate([
{$group: {
_id: null,
prices: {$sum: "$price"}
}}
])
Here is what I would like to obtain:
db.items.aggregate([
{$group: {
_id: null,
prices: {$sum: "$price"*"$quantity"}
}}
])
You don't need to use map-reduce for this. You can use aggregation framework and combine multiple aggregation operators. You almost got it you were just missing the final piece - $multiply operator:
db.items.aggregate([{
"$group" : {
"_id" : null,
"prices" : {
"$sum" : {
"$multiply" : ["$price", "$quantity"]
}
}
}
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With