Home > Software design >  MongoDb Aggregate transform common objects in arrays
MongoDb Aggregate transform common objects in arrays

Time:12-02

I'm stuck in an issue:

I need to transform:

[ {a:1 , b:2 , c:3} , {a:5, b:6, c:7} ]

Into:

[{a:[1,5], b:[2,6] , c: [3,7]}]

Just look for common keys and group that.

I'm not sure if i should use $project $reduce or $group. Someone have a tip?

CodePudding user response:

To do this, we should change the object to array first to be abble to group by key. You can check it here.

{
  "$project": {
    "_id": 0 // First we have to eliminate the _id and all the other fields that we dont want to group
  }
},
{
  "$project": {
    "arr": {
      "$objectToArray": "$$ROOT"
    }
  }
},

Then we sould unwind this array and group the keys.

{
  "$unwind": "$arr"
},
{
  "$group": {
    "_id": "$arr.k",
    "field": {
      "$push": "$arr.v"
    }
  }
}

Finally we remap the information with the desired output.

{
  $replaceRoot: {
    newRoot: {
      $arrayToObject: [
        [
          {
            k: "$_id",
            v: "$field"
          }
        ]
      ]
    }
  }
}
  • Related