Home > Back-end >  want to group mongoDB documents by user. but after grouping, I don't want the user's mail
want to group mongoDB documents by user. but after grouping, I don't want the user's mail

Time:04-11

My sample data:

[
    {
        'user': '[email protected]',
        'AddressLine': 'jntgt',
        'vat': 'gfgf',
        'Companyname': 'gfgfg',
        'countryName': 'mexico',
        'AddressTitle': 'ev',
    },
    {
        'user': '[email protected]',
        'AddressLine': 'gthh',
        'vat': 'gfgf',
        'Companyname': 'gfgfg',
        'countryName': 'usa',
        'AddressTitle': 'ev',
    },
    {
        'user': '[email protected]',
        'AddressLine': 'gdgg',
        'vat': 'gfgf',
        'Companyname': 'ljjjhg',
        'countryName': 'Angola',
        'AddressTitle': 'ev',
    },
];

I want the result to look like this:

[
    {
        'user': '[email protected]',
        'addresses': [
            {
                'AddressLine': 'jntgt',
                'vat': 'gfgf',
                'Companyname': 'gfgfg',
                'countryName': 'mexico',
                'AddressTitle': 'ev',
            },
            {
                'AddressLine': 'gthh',
                'vat': 'gfgf',
                'Companyname': 'gfgfg',
                'countryName': 'usa',
                'AddressTitle': 'ev',
            },
        ],
    },
    {
        'user': '[email protected]',
        'addresses': [
            {
                'AddressLine': 'gdgg',
                'vat': 'gfgf',
                'Companyname': 'ljjjhg',
                'countryName': 'Angola',
                'AddressTitle': 'ev',
            },
        ],
    },
]

How should mongodb aggregation code be? I tried this:

[
    {
        $group: {
            _id: '$user',
            addresses: { $push: '$$ROOT' },
        },
    },
    {
        $project: {
            user: '$_id',
            addresses: 1,
        },
    },
];

ok. but The user I grouped in root appears again. how can i remove user when i group.

CodePudding user response:

You can do this in multiple ways, the easiest way IMO is to just add another $project stage at the end that excludes that field, like so:

db.collection.aggregate([
  {
    $group: {
      _id: "$user",
      addresses: {
        $push: "$$ROOT"
      }
    },
    
  },
  {
    $project: {
      user: "$_id",
      addresses: 1,
      
    }
  },
  {
    $project: {
      _id: 0,
      "addresses.user": 0
    }
  }
])

Mongo Playground

  • Related