Search code examples
springmongodbnosql-aggregation

Spring MongoDB Aggregation Group


I want to group data by condition. Here is the data

[
  {
    name: AAA,
    age: 14,
    country: us
  },
  {
    name: BBB,
    age: 13,
    country: us
  },
  {
    name: CCC,
    age: 12,
    country: null
  },
  {
    name: DDD,
    age: 12,
    country: null
  }
]

If country is null, group by age If country is not null, group by country

I would like to get the result like below

{
  country: us
  [
    {
      name: AAA,
      age: 13
    },
    {
      name: BBB,
      age: 14
    }
  ]
},
{
  age: 12,
  country: null
  [
    name: CCC,
    name: DDD,
  ]
}

Hope to get help


Solution

  • You try this method

     [
          {
            $group: {
              _id: "$country",
              people: {
                $push: {
                  name: "$name",
                  age: "$age"
                }
              },
              age: {
                $addToSet: "$age"
              }
            }
          },
          {
            $project: {
              _id: 0,
              country: "$_id",
              people: 1,
              age: {
                "$cond": {
                  "if": {
                    "$eq": [
                      {
                        $size: "$age"
                      },
                      1
                    ]
                  },
                  "then": {
                    $arrayElemAt: [
                      "$age",
                      0
                    ]
                  },
                  "else": 0
                }
              }
            }
          }
        ]
    

    mongoplayground