Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to clean an array from empty objects in mongodb?

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!