1

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":[],
    }]
}]

1 Answer 1

2

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

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.