0

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
}
Losercoder2345
  • 61
  • 1
  • 10

1 Answers1

1

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"
      }
    }
  }
}
Lahiru Tennakoon
  • 621
  • 1
  • 6
  • 8