Home > Blockchain >  How to group data by key without $unwind nor $group stage in mongodb aggregation
How to group data by key without $unwind nor $group stage in mongodb aggregation

Time:02-08

Can anyone help me to group the data by key without using $unwind nor $group stage ? The reason why I don't want to use $unwind nor $group stage is because I want to be able to use the pipeline in a updateMany(filter, pipeline) operation so the stages I can use are limited to: $addFields (= $set), $project (= $unset) and $replaceRoot (= $replaceWith).

The input data looks like this:

[
  {
    key: "alpha",
    value: {
      name: "foo",
    },
  },
  {
    key: "beta",
    value: {
      name: "bar",
    },
  },
  {
    key: "alpha",
    value: {
      name: "baz",
    },
  },
]

The result I would like to get:

[
  {
    key: "alpha",
    values: [
      {
        name: "foo",
      },
      {
        name: "baz",
      },
    ],
  },
  {
    key: "beta",
    values: [
      {
        name: "bar",
      },
    ],
  },
]

I believe that it's doable by using $reduce but I'm newbie with mongodb aggregation so I'm struggling to accumulate objects in array conditionally.

Thanks

CodePudding user response:

    [
        {
            $set: {
                keys: { $setUnion: [ "$array.key" ] }
            
            }
        },
 
        {
            $set: {
                newarray : {
                    $map : {
                        input : "$keys",
                        in : {
                            key : "$$this",
                            values : {
                                $map : {
                                    input : {
                                        $filter : {
                                            input : "$array",
                                            as : "elem",
                                            cond : {
                                                $eq : [
                                                    "$$elem.key",
                                                    "$$this"
                                                ]
                                            }
                                        }},
                                        as : "vals",
                                        in : {
                                            name : "$$vals.value.name"
                                        }
                                    }
                                
                            }
                        }
                    }
                }
            }
        }
    ]


Try it. https://mongoplayground.net/p/m1UUvt5QNgg Or more compact version: https://mongoplayground.net/p/bFrSiyc5nSc

  •  Tags:  
  • Related