Is there a way to not $project keys that have an empty array in the mongodb aggregation pipeline?

700 views Asked by At

I'm getting some [] values for some of my returned key results, but I want to make it so that the keys with [] values are never returned at all. This needs to be in the Aggregation Pipeline.

Ex:

{
"_id": "5e42fb9b74753bd02c86ca2c",
"key_one": 'something',
"key_two": 'another thing',
"key_three": [],
"key_four": [],
"key_five": 'one more time
}

What I want to be returned:

{
 "_id": "5e42fb9b74753bd02c86ca2c",
"key_one": 'something',
"key_two": 'another thing',
"key_five": 'one more time
}
1

There are 1 answers

0
Lahiru Tennakoon On

Use the "$$REMOVE" variable inside the $project stage to remove the field if it's an empty array.

{
  $project: {
    key_three: {
      $cond: {
        if: {
          $ne: ["$key_three", []]
        },
        then: "$key_three",
        else: "$$REMOVE"
      }
    },
    key_four: {
      $cond: {
        if: {
          $ne: ["$key_four", []]
        },
        then: "$key_four",
        else: "$$REMOVE"
      }
    }
  }
}