猫鼬,Node.js从一堆文件中得到一个字段的总和

Ber*_*olo 3 mongoose mongodb node.js

我有这个猫鼬方法/查询,它从某个用户中查找所有“收入”,但前提是“收入”的日期在当月内。

码:

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);
}
Run Code Online (Sandbox Code Playgroud)

结果:

[
{

"_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"
}

]
Run Code Online (Sandbox Code Playgroud)

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

现在,我想从这些文档中获取每个“金额”字段的总和。

因此,在这种情况下,总和为1050。

我如何在猫鼬中实现这一目标?

非常感谢任何帮助,欢呼。

Rav*_*rti 6

您可以使用猫鼬聚合管道来计算amount多个文档的总和。

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

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

希望这可以帮助!

  • 需要“$and”吗?默认的“and”表达式有多个条件,不是吗?所以 `$match : {owner: userId, date: { $gte: start, $lt: end } }` 应该是一样的,对吧? (3认同)