Aggregation group with nested array

I need help with aggregation.
I have a document like this:

{
   group: {
      code: 1
   },
   customerID: 11111
}

and I need to create new document grouped by group code with related customer IDs as array

{
  groupCustomerRelation: [
    group: {
      code: 1
    },
    customerID: [
      11111,
      22222,
      33333
    ]
  ]
}

how can I achieve this?

Hi @Daniel_Sorkin ,

and I need to create new document grouped by group code with related customer IDs as array
how can I achieve this?

You should be able to do this as follows:

use('test')
db.foo.drop();
db.foo.insertMany([
{ group: { code: 1 }, customerID: 11111 },
{ group: { code: 1 }, customerID: 22222 },
{ group: { code: 1 }, customerID: 33333 }
]);
db.foo.aggregate([
  { $group: {
    _id: "$group.code",
    customerID: { $push: "$customerID"}
  }},
  { $project: { 
    _id: 0,
    groupCustomerRelation: {
      group: { code: "$_id" },
      customerID: "$customerID"
    }    
  }}
])
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.