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.
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!
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