Home > Software design >  Mongo Group By 4 levels down
Mongo Group By 4 levels down

Time:10-22

Playground

I have a list with 4 props. I want the result to be:

ProjectName
   PartnerName
      Date
         Time1
         Time2
         Time3

ex.

PROJECT-AA
   PART-AA
      2021-01-01 
           21:00:00
           22:00:00
      2021-01-02 
           21:00:00
   PART-BB
       2021-01-01
           21:00:00

I can group the 1st level and add the props to a new prop with $push, but after that I cant group the next levels..

And how can I concatenate the times by partner?

thanks.

CodePudding user response:

For your case, you just need to do with 2 $group.

  1. $group by "ProjectName, PartnerName, Date, $push Time inside.
  2. $group by "ProjectName, PartnerName, $push Date, Time inside.
  3. $group by ProjectName, $push PartnerName, DateTime inside. You can then continue to wrangle you data to your expected form.
db.collection.aggregate([
  {
    "$group": {
      "_id": {
        "ProjectName": "$ProjectName",
        "PartnerName": "$PartnerName",
        "Date": "$Date"
      },
      Time: {
        $push: "$Time"
      }
    }
  },
  {
    "$group": {
      "_id": {
        "ProjectName": "$_id.ProjectName",
        "PartnerName": "$_id.PartnerName"
      },
      DateTime: {
        $push: {
          Date: "$_id.Date",
          Time: "$Time"
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.ProjectName",
      partner: {
        $push: {
          PartnerName: "$_id.PartnerName",
          DateTime: "$DateTime"
        }
      }
    }
  }
])

Here is the Mongo Playground for your reference.

  • Related