0

For one of my project, I am working on MongoDB database and Mongoose as ODM in nestjs project.

One of my collection is looks like this data:

[
  {
    _id: '56cb91bdc3464f14678934ca',
    organization: 'New Circle Ltd',
    rooms: [
      {
        name: 'Alex',
        workId: 'abc',
      },
      {
        name: 'John',
        workId: 'cde',
      },
      {
        name: 'John',
        workId: 'abc',
      },
      {
        name: 'Alex',
        workId: 'cdlw',
      },

      {
        name: 'Alex',
        workId: 'rps',
      },
    ],
  },
];

The requirement is to get one data by id and the data should be like the data provided bellow.

{
    _id: '56cb91bdc3464f14678934ca',
    organization: 'New Circle Ltd',

    rooms: [
      {
        name: 'Alex',
        workIds: ['abc', 'cdlw', 'rps'],
      },
      {
        name: 'John',
        workIds: ['cde', 'abc'],
      },
    ],
  },

Please suggest me how can I get this data

  • 1
    Does this answer your question? [MongoDB group by array inner-elements](https://stackoverflow.com/questions/21509045/mongodb-group-by-array-inner-elements) – Charchit Kapoor Aug 25 '22 at 04:02
  • The common way of working with this is to `$unwind`, then `$group` on a field and you `$push` (or `$addToSet`) the data into an array. – prasad_ Aug 25 '22 at 05:58

0 Answers0