Search code examples
mongodbaggregation-framework

How to group null values separately?


Data:

db={
  "Test": [
    {
      "x": "a"
    },
    {
      "x": "a",
      "y": 1
    },
    {
      "x": "a",
      "y": 2
    }
  ]
}

When aggregating like this:

db.Test.aggregate([
  {
    "$group": {
      "_id": {
        "x": "$x"
      },
      "y": {
        "$addToSet": "$y"
      }
    }
  }
])

... I expectedly get this:

[
  {
    "_id": {
      "x": "a"
    },
    "y": [
      2,
      1
    ]
  }
]

But I want to group those xs separately where y is null and get this result:

[
  {
    "_id": {
      "x": "a"
    },
    "y": []
  },
  {
    "_id": {
      "x": "a"
    },
    "y": [
      1,
      2
    ]
  }
]

Is this possible?

Playground


Solution

  • Playground

    db.Test.aggregate([
      {
        "$group": {
          "_id": {
            "x": "$x",
            "z": {
              $cond: [
                {$ifNull: ["$y", false]},
                true,
                false
              ]
            }
          },
          "y": {
            "$addToSet": "$y"
          }
        }
      }
    ])