【问题标题】:mongoose sum a value across all documents猫鼬对所有文档求和
【发布时间】:2017-01-28 01:16:47
【问题描述】:

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

 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}

我该怎么做?

【问题讨论】:

    标签: javascript mongodb mongoose aggregation-framework mongodb-aggregation


    【解决方案1】:

    使用$match$group 运算符尝试使用aggregation framework,即类似这样的东西

    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
    }
    

    【讨论】:

    • 这也适用于猫鼬吗?导致tickets.aggregate([{ $match: { time: {$gte: a, $lte: tomorrow} } }, { $group: { _id: null, amount: { $sum: "$amount" } } }] ).then(function (test) { 对我不起作用,因为它没有执行它。
    • tickets 是我的猫鼬模型是的。你会看看teamviewer吗? ,无论如何,我会看看,并接受你的回答:)
    • 我猜你的回调应该有两个参数(错误和结果)。 This SO 问题展示了如何将聚合管道与猫鼬一起使用 - 希望对您有所帮助。否则我今晚会尝试自己测试一下
    • 将继续让它工作。我将 console.logging 在结果中,但它从未执行过。
    • @DAXaholic 我有两个小数点存储为字符串的金额我如何使用猫鼬获得所有记录的总和...?
    猜你喜欢
    • 2016-12-17
    • 1970-01-01
    • 2013-10-21
    • 2016-03-03
    • 2021-12-21
    • 2014-05-30
    • 2020-08-12
    • 2014-05-29
    • 2021-02-11
    相关资源
    最近更新 更多