Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, Node.js get sum of a field from a bunch of documents

I have this mongoose method/query which finds all 'incomes' from a certain user but only if the dates of the 'incomes' are within the current month.

Code:

module.exports.getMonthlyIncome = function(userId, callback){
const now = new Date();

const year = now.getFullYear();
const month = now.getMonth();
const date = now.getDate();

const start = new Date(year, month, 1);
const end = new Date(year, month, 30);

Income.find({owner: userId, date: { $gte: start, $lt: end }}, callback);
}

Result:

[
{

"_id": "58cc9ee50fe27e0d2ced5193",
"amount": 600,
"description": "Ripco Salary",
"owner": "58cc9e950fe27e0d2ced5192",
"__v": 0,
"date": "2017-03-17T00:00:00.000Z"
},

{

"_id": "58ccc3cfca6ea10980480d42",
"amount": 450,
"description": "Another Ripped co salary",
"owner": "58cc9e950fe27e0d2ced5192",
"__v": 0,
"date": "2017-03-26T00:00:00.000Z"
}

]

Result is as expected, gives me the 2 income documents belonging to a certain user during the month.

Now, I want to get the total sum of every 'amount' field from these documents.

So in this case, the sum would be 1050.

How would I achieve this in Mongoose?

Any help is greatly appreciated, cheers.

like image 529
Berimbolo Avatar asked Dec 14 '22 00:12

Berimbolo


1 Answers

You can use mongoose Aggregation pipeline to calculate the sum of amount across multiple document.

you need to use $match, to match the query condition, $group to calculate sum across multiple documents.

Income.aggregate([{
    $match : { $and : [ {owner: userId}, {date: { $gte: start, $lt: end } }] },
},{
    $group : {
        _id : null,
        total : {
            $sum : "$amount"
        }
    }
}],callback);

Hope this helps!

like image 55
Ravi Shankar Bharti Avatar answered Dec 21 '22 10:12

Ravi Shankar Bharti