Mongoose如何对所有文档的某个值求和?

11

我想要计算所有名称为amount的列在符合我的查询条件的文档中的数量。

 tickets.count({time: {$gte: a}, time: {$lte: tomorrow}}).then(function (numTickets) {

如何获取名为“amount”的文档列的总结果?

例如,如果我有:

{ time: 20, amount: 40}
{ time: 40, amount: 20}

它会返回总金额(60)吗?

请记住,我需要在查询中使用{time: {$gte: a}, time: {$lte: tomorrow}

我应该怎么做?

1个回答

27

使用聚合框架$match以及$group运算符来尝试一下,例如:

db.tickets.aggregate([
    { $match: { time: {$gte: a, $lte: tomorrow} } },
    { $group: { _id: null, amount: { $sum: "$amount" } } }
])

例如,使用此类测试数据。
/* 1 */
{
    "_id" : ObjectId("57e0ed40828913a99c2ceb46"),
    "time" : 20,
    "amount" : 40
}

/* 2 */
{
    "_id" : ObjectId("57e0ed40828913a99c2ceb47"),
    "time" : 40,
    "amount" : 20
}

/* 3 */
{
    "_id" : ObjectId("57e0ed40828913a99c2ceb48"),
    "time" : 50,
    "amount" : 10
}

/* 4 */
{
    "_id" : ObjectId("57e0ed40828913a99c2ceb49"),
    "time" : 10,
    "amount" : 5
}

一个(带有虚拟时间范围的)管道如下所示:
db.tickets.aggregate([
    { $match: { time: {$gte: 20, $lte: 40} } },
    { $group: { _id: null, amount: { $sum: "$amount" } } }
])

会给您一个如下的结果

/* 1 */
{
    "_id" : null,
    "amount" : 60
}

Pipeline in action


这个在mongoose上也能用吗?原因 tickets.aggregate([{ $match: { time: {$gte: a, $lte: tomorrow} } }, { $group: { _id: null, amount: { $sum: "$amount" } } }]).then(function (test) { 对我来说行不通,它没有执行。 - maria
票务是我的Mongoose模型,你能在TeamViewer上看一下吗?无论如何,我会查看并接受你的答案 :) - maria
你的回调函数应该有两个参数(用于错误和结果)。这个 SO 问题展示了如何使用mongoose的聚合管道 - 希望能帮到你。否则我今晚会尝试测试它。 - DAXaholic
我会继续让它工作。我在结果中使用console.logging,但它从未被执行。 - maria
@DAXaholic 我有一些以字符串形式存储的带有两位小数的金额数据,我该如何使用mongoose获取所有记录的总和呢? - Muhammad Usama Mashkoor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接