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

2
  • 1
    Does this answer your question? MongoDB group by array inner-elements Commented Aug 25, 2022 at 4: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. Commented Aug 25, 2022 at 5:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.