猫鼬对所有文档求和一个值

mar*_*ria 8 javascript mongoose mongodb aggregation-framework mongodb-aggregation

我希望计算与我的查询匹配的文档中名称数量的所有列,

 tickets.count({time: {$gte: a}, time: {$lte: tomorrow}}).then(function (numTickets) {
Run Code Online (Sandbox Code Playgroud)

如何获得称为金额的文档列的总结果?

例如,如果我有:

{ time: 20, amount: 40}
{ time: 40, amount: 20}
Run Code Online (Sandbox Code Playgroud)

它会返回总金额(60)?

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

我该怎么做?

DAX*_*lic 19

使用$match$group运算符在聚合框架中进行尝试,即像这样

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

例如像这样的测试数据

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

如下所示的管道(具有虚拟时间范围)

db.tickets.aggregate([
    { $match: { time: {$gte: 20, $lte: 40} } },
    { $group: { _id: null, amount: { $sum: "$amount" } } }
])
Run Code Online (Sandbox Code Playgroud)

会给你这样的结果

/* 1 */
{
    "_id" : null,
    "amount" : 60
}
Run Code Online (Sandbox Code Playgroud)

管道在行动