繁体   English   中英

如何在 MongoDB 的聚合管道中重新组合(或合并)对象?

[英]How to regroup (or merge) objects in aggregation pipeline in MongoDB?

我目前有一个聚合管道:

db.getCollection('forms').aggregate([
    { $unwind: //unwind },
    { 
        $match: {
            //some matches
        }   
    },
    {
        $project: {
            //some projections
        }
    }, 
    {        
        //Finally, im grouping the results
        $group: {
            _id: {
                year: { $year: '$createdAt' },
                month: { $month: '$createdAt' },
                raceEthnicity: '$demographic.raceEthnicity'
            },
            count: { $sum: 1 },
    }
]

我目前的结果类似于:

[{
    "_id" : {
        "year" : 2020,
        "month" : 11,
        "raceEthnicity" : "Asian"
    },
    "count" : 1.0
},
{
    "_id" : {
        "year" : 2020,
        "month" : 11,
        "raceEthnicity" : "Multiracial"
    },
    "count" : 3.0
},
{
    "_id" : {
        "year" : 2020,
        "month" : 11,
        "raceEthnicity" : "White"
    },
    "count" : 3.0
},
{
    "_id" : {
        "year" : 2020,
        "month" : 10,
        "raceEthnicity" : "White"
    },
    "count" : 33.0
}]

有没有办法在管道上添加一个新阶段以将同一年/月的结果“合并”到一个对象中? 我想实现以下目标:

{
    "_id" : {
        "year" : 2020,
        "month" : 11,
    },
    "Asian" : 1.0,
    "Multiracial": 3.0,
    "White": 1.0
},
{
    "_id" : {
        "year" : 2020,
        "month" : 10,
    },
    "White": 33
}

是否可以? 我怎样才能做到这一点?

将此添加到您的聚合管道中。

db.collection.aggregate([
   { $set: { "data": { k: "$_id.raceEthnicity", v: "$count" } } },
   { $group: { _id: { year: "$_id.year", month: "$_id.month" }, data: { $push: "$data" } } },
   { $set: { "data": { $arrayToObject: "$data" } } },
   { $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", "$data"] } } },
   { $unset: "data" }
])

与@wak786 的解决方案不同,您不需要在设计时了解所有种族。 它适用于任意种族。

将这些阶段添加到您的管道中。

db.collection.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        "$mergeObjects": [
          "$$ROOT",
          {
            $arrayToObject: [
              [
                {
                  k: "$_id.raceEthnicity",
                  v: "$count"
                }
              ]
            ]
          }
        ]
      }
    }
  },
  {
    "$group": {
      "_id": {
        year: "$_id.year",
        month: "$_id.month",
        
      },
      "Asian": {
        "$sum": "$Asian"
      },
      "Multiracial": {
        "$sum": "$Multiracial"
      },
      "White": {
        "$sum": "$White"
      }
    }
  }
])

下面是 mongo 游乐场链接。 我已将您管道的当前结果作为查询的输入。

在这里试试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM