【问题标题】:MongoDB array[] sum-functionMongoDB数组[]求和函数
【发布时间】:2020-08-16 12:18:16
【问题描述】:

我正在尝试计算数据库中每种货币的所有余额的总和。我必须按货币对其进行分组,但 $sum 返回了一个异常。任何想法如何解决它?

异常:查询失败:(Location40237) $sum 累加器是 一元运算符

    db.getCollection("people").aggregate([
    {
        $group: {
            _id: { currency:  "$credit.currency" },
            sumCur: { $sum: [ { $toDouble:  "$credit.balance" }]}

        }
    }
])

数据模型示例:

{ 
    "_id" : ObjectId("5ea970747cd4ac05869977ec"), 
    "sex" : "Male", 
    "first_name" : "Wayne", 
    "last_name" : "Fields", 
    "job" : "Speech Pathologist", 
    "email" : "wfields0@diigo.com", 
    "location" : {
        "city" : "Oyo", 
        "address" : {
            "streetname" : "Beilfuss", 
            "streetnumber" : "860"
        }
    }, 
    "description" : "vulputate justo in blandit ultrices enim lorem ipsum dolor sit amet consectetuer adipiscing elit proin interdum mauris", 
    "height" : "152.38", 
    "weight" : "66.81", 
    "birth_date" : "1990-02-21T02:55:03Z", 
    "nationality" : "Nigeria", 
    "credit" : [
        {
            "type" : "switch", 
            "number" : "6759888939100098699", 
            "currency" : "COP", 
            "balance" : "5117.06"
        }
    ]
}

【问题讨论】:

    标签: arrays mongodb mongodb-query aggregation-framework


    【解决方案1】:

    $sum 在传递数组时需要一个标量数值。您需要先使用$unwind,因为不同的数组元素也可能有不同的货币:

    db.collection.aggregate([
        { $unwind: "$credit" },
        {
            $group: {
                _id: {
                    currency: "$credit.currency"
                },
                sumCur: {
                    $sum: { $toDouble: "$credit.balance" }
                }
            }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2015-07-26
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多