Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoDB, sum the product of two fields

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"}
    }}
])
like image 220
M4rk Avatar asked Oct 23 '25 14:10

M4rk


1 Answers

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"]
            }
        }
    }
}]);
like image 192
Christian P Avatar answered Oct 25 '25 13:10

Christian P