Losercoder2345
Losercoder2345

Reputation: 71

How to remove empty string and arrays from objects inside an array? MongoDB Aggegation

I want to delete the empty strings and empty arrays within a document. Is there a way to do this with the MongoDB Aggregation Framework? Here is an example of an incoming document:

"item": [{
    "array_objects":[{
        "text": '',
        "second_text": '',
        "empty_array": [],
        "empty_array_2":[],
    }]
}]

Upvotes: 1

Views: 427

Answers (1)

Tiya Jose
Tiya Jose

Reputation: 1419

If you want to project all the fields that are not empty string or empty array, use $filter

You can try the below aggregation query:

db.collection.aggregate([
  {
    $unwind: "$item"
  },
  {
    $unwind: "$item.array_objects"
  },
  {
    $project: {
      item: {
        $arrayToObject: {
          $filter: {
            input: {
              $objectToArray: "$item.array_objects"
            },
            cond: {
              $and: [
                {
                  $ne: [
                    "$$this.v",
                    ""
                  ]
                },
                {
                  $ne: [
                    "$$this.v",
                    []
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
])

MongoDB playground

Upvotes: 2

Related Questions