0

Afterwards an aggregation in mongodb I get this results:

[
  my_arr:[
    {
      id: ObjectId('618f7ef057c2923be10d1111')
      //other stuff
    },
    {},
    {},
  ]
]

Is there a way to remove the empty object directly in the aggregation? or it is necessary to do it server side? I get that after doing an unwind and a group.

1 Answer 1

2

You can add a new aggregation stage ( $project, $set or $addFields) with $filter like this:

{
  "$project": {
    "my_arr": {
      "$filter": {
        "input": "$my_arr",
        "as": "a",
        "cond": {
          "$ne": [
            "$$a",
            {}
          ]
        }
      }
    }
  }
}

This filter get only objects into the array where the object itself is not empty (i.e. is not {})

Example here

Also $set example and $addFields example

Also, you can use $$this to refer the object instead of value from as. Example here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.