【问题标题】:How to combine two objects in mongodb aggregation project stage?如何在mongodb聚合项目阶段合并两个对象?
【发布时间】:2020-01-23 03:34:06
【问题描述】:

我的聚合管道中有以下结构数组。尝试了合并对象和 setUnion 运算符。

{ 
  combs:[
    [
      {
        name:"A",
        c_type:"A"
      },
      {
        type:"visual",
        severity:"Normal"
      }
    ],
    [
      {
        name:"B",
        c_type:"B"
      },
      {
        type:"visual",
        severity:"Normal"
      }
    ]
  ]
}

我预计以下结果会产生一些统计数据。请帮帮我。

{ 
  combs:[
    {
      name:"A",
      c_type:"A",
      type:"visual",
      severity:"Normal"
    }
    {
      name:"B",
      c_type:"B",
      type:"visual",
      severity:"Normal"
     }
  ]
}

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用这个聚合查询

    db.collection.aggregate([
         { $unwind: "$combs" },
         { $addFields: { combs: { $mergeObjects: "$combs" }}},
         { $group: { _id: "$_id", combs: { $push: "$combs" }} }
     ])
    

    【讨论】:

    • 不使用$unwind操作是否可以实现? @Ashok
    【解决方案2】:

    “是否可以不使用$unwind操作来实现?”

    嗯,是的。只要您的 arrays of arrays 结构始终以这种方式映射,那么您实际上只需要管道中的一个阶段:

    db.collection.aggregate([
      { "$addFields": {
         "combs": {
           "$map": {
             "input": "$combs",
             "in": { "$mergeObjects": "$$this" }
           }
         }
      }}
    ])
    

    所以实际上$map 操作符在这里作为处理每个数组元素的比$unwind 更有效的方法。此外,由于 $mergeObjects 期望 “对象数组”,这就是 数组数组 中的每个元素的实际情况。因此,只需在数组的每个 outer 成员上使用 { "$mergeObjects": "$$this" }

    根据您提供的数据生成输出:

    {
            "_id" : ObjectId("5d8865c273375a6a4cc9e76a"),
            "combs" : [
                    {
                            "name" : "A",
                            "c_type" : "A",
                            "type" : "visual",
                            "severity" : "Normal"
                    },
                    {
                            "name" : "B",
                            "c_type" : "B",
                            "type" : "visual",
                            "severity" : "Normal"
                    }
            ]
    }
    

    通常,您应该始终更喜欢$map 或其他数组运算符等内联处理器,而不是$unwind(如果适用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多