【问题标题】:Mongodb sum by field existsMongodb 字段总和存在
【发布时间】:2020-05-17 06:00:20
【问题描述】:

我有以下集合,其中字段数量随时间变化。

{ 
    "_id" : "9235@7421",
    "usine" : { "0" : 0, "1" : 3, "2" : 1, "3" : 2, "4" : 0, "5" : 3, "6" : 1, "7" : 0, "8" : 2, "9" : 1 }, 
    "ecole" : { "0" : 1, "1" : 0, "2" : 0, "3" : 1, "4" : 1, "5" : 0, "6" : 0, "7" : 1, "8" : 0, "9" : 1 }
}

以下查询可以正常工作。它计算所有字段的值的总和。

db.lieux.aggregate([
    {
        $match: {
            "_id": "9235@7421"
        }
    },
    {
        $project: {
            "MontoSum": {
                $sum: {
                    $add: [
                        "$usine.0", "$usine.1", "$usine.2", "$usine.3", "$usine.4", "$usine.5", "$usine.6", "$usine.7", "$usine.8", "$usine.9", "$ecole.0", "$ecole.1", "$ecole.2", "$ecole.3", "$ecole.4", "$ecole.5", "$ecole.6", "$ecole.7", "$ecole.8", "$ecole.9"]
                }
            }
        }
    }
])

结果是:{ "_id" : "9235@7421", "MontoSum" : 18 },这是正确的。

我的问题是:

1) 有没有更好的方法来查询我的集合字段的值的总和?我觉得我的查询太长了,一点都不聪明。

2) 当文档缺少我查询中的字段时(例如缺少字段“6”),返回值为 { "_id" : "9235@7421", "MontoSum" : 0 }是不正确的。在我看来, sum 函数不喜欢缺少字段。在我的情况下如何使用类似 $ifNull 的东西?

非常感谢

【问题讨论】:

    标签: mongodb sum


    【解决方案1】:
    1. 我们可以使用$objectToArray$map 等运算符来操作对象结构:
    {
        $project: {
            "MontoSum": {
                $sum: {
                    $concatArrays: [
                        {
                            $map: {
                                input: {$objectToArray: "$usine"},
                                as: "usine",
                                in: "$$usine.v"
                            }
                        },
                        {
                            $map: {
                                input: {$objectToArray: "$ecole"},
                                as: "ecole",
                                in: "$$ecole.v"
                            }
                        }
                    ]
                }
            }
        }
    }
    

    现在这并不是最短的表达式,但它可以缩放。

    1. 使用这些运算符还可以解决此问题,因为您正在对未定义的值求和导致意外行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2023-01-13
      相关资源
      最近更新 更多