Group documents by common field and bucket by month

I would like to group documents based on a reference field (profileID), and then group posts for each month of the past year into an array of documents. Here is the current schema:

[
  {
    profileId: 123,
    datePosted: '2022-01-01',
    content: 'this is post content'
  },
  {
    profileId: 123,
    datePosted: '2022-01-09',
    content: 'this is a different posts content'
  },
  {
    profileId: 456,
    datePosted: '2022-02-03',
    content: 'this is some other posts content'
  },
]

Here is the desired schema:

[
  {
    profileId: 123,
    postsByMonth: [
      {
        month: '2022-01-01',
        posts: [
          {
            datePosted: '2022-01-01',
            content: 'this is post content'
          },
          {
            datePosted: '2022-01-09',
            content: 'this is a different posts content'
          },
        ]
      },
    ]
  }, 
  {
    profileId: 456,
    postsByMonth: [
      {
        month: '2022-02-01',
        posts: [
          {
            datePosted: '2022-02-03',
            content: 'this is some other posts content'
          }
        ]
      }
    ]
  }
]

What is the best way to accomplish this using aggregation? Thank you in advance!!

Best would be two $group stages, first one groups by profileId and month of datePosted, and then the second groups by profileId pushing posts into an array…

Asya

Thank you! Grouping by two fields during the first stage was just what I needed.

1 Like

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