Mongoose,Node.js从一堆文件中获得一个字段的总和

我有这种mongoose方法/查询,它可以查找某个用户的所有“收入”,但只有当“收入”的date在当前月份内。

码:

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); } 

结果:

 [ { "_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" } ] 

结果如预期,给我一个月内属于某个用户的2个收入文件。

现在,我想从这些文件中获得每个“数量”字段的总和。

所以在这种情况下,总和将是1050。

我将如何实现这个mongoose?

任何帮助,不胜感激,欢呼声。

有两种方法可以做到这一点。

1.使用聚合查询:看起来你是mongodb的新手。 所以,我不会为你build议这个方法。 这种方法在另一个答案中正确地被覆盖,并且应该完全正常工作。 检查出来!

2.使用下划线节点 :

重写你的代码:

 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); // Including underscore-node const _ = require('underscore-node'); Income.find({owner: userId, date: { $gte: start, $lt: end }}, function(err, results){ if (err) { //handle error } let sum = _.reduce(results, function(memo, reading){ return memo + reading.amount; }, 0); // Explaination: // reduce() accepts an array and a callback function. // So, we are passing the array in "results" // In the callback function, do not touch "memo" variable // Every single object in "results" array will be passed // to callback function in the "reading" variable }); 

希望这个代码可以帮助你!

您可以使用mongoose Aggregationpipe道来计算跨多个文档的amount总和。

您需要使用$匹配来匹配查询条件$ group来计算跨多个文档的总和。

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

希望这可以帮助!