【问题标题】:$group result as the key value pair mongo db$group 结果作为键值对 mongodb
【发布时间】:2020-06-27 05:39:12
【问题描述】:

$group 阶段之前的管道阶段计算文档,如下所示

cycle_id | entity1 | entity 2
   1     |    0    |    1
   1     |    1    |    5
   2     |    0    |    3

我可以使用下面的脚本对它们进行分组

{ 
        "$group" : { 
            "_id" : "$cycle_id", 
            "entity1" : { 
                "$sum" : "$entity1"
            }, 
            "entity2" : { 
                "$sum" : "$entity3"
            }, 
            "entity3" : { 
                "$sum" : "$entity3"
            }
        }
    }

生成的输出如下:

cycle_id | entity1 | entity 2
   1     |    1    |    6
   2     |    0    |    3

但我正在寻找的是可以像键值对数组一样投射它的东西

{
 1:{
  entity1: 1,
  entiry2: 6
 },
 2:{
  entity1: 3,
  entiry2: 4
 }
}

有没有办法可以达到上述结果。我试着环顾$arrayToObject,但还不太成功。

谢谢, 尼克西特

【问题讨论】:

  • 这能回答你的问题吗? How to use field value as key name in Mongodb result 将其设为 dup,检查是否已实现 :: mongoplayground.net/p/j_c0_RzfCoU
  • 不,这不是一个重复,因为它返回的是字典数组而不是一个字典。
  • 您提到“键值数组”对,不是字典数组吗?聚合总是返回一个数组,如果你想要一个单个字典的数组,你可以使用@whoami 实现,并使用 $group 和 $mergeObjects
  • @NixitPatel:对于任何读取管道,无论哪种聚合都将始终返回一个数组empty arrayarray with one objectarray with multiple objects !您需要在代码中获取响应数组的第一个元素。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

查询:

db.collection.aggregate([
    /** Group without any condition and merge all documents (Converted objects) into an object */
    {
      $group: {
        _id: "",
        data: {
          $mergeObjects: {
            $arrayToObject: [ [ { k: { $toString: "$_id" }, v: { "entity1": "$entity1", "entity2": "$entity2" } } ] ]
          }
        }
      }
    },
    /** Replace `data` field as a root of the document */
    {
      $replaceRoot: { newRoot: "$data" }
    }
  ])

测试: mongoplayground

参考:aggregation-pipeline

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2018-03-27
    • 1970-01-01
    相关资源
    最近更新 更多