Losercoder2345
Losercoder2345

Reputation: 71

How to remove empty string and arrays from objects inside an object with the mongodb aggregation pipeline?

I want to remove any document that has an empty text string from an object within an object. Is there a way to do this with the MongoDB Aggregation Framework? In this case it will be the text within object_1 and object_2.

"array_of_objects":[{
    "city": "Seattle",
    "array_1": [],
    "object_1":{
        "name": "Mandy",
        "text" "",
    },
    "object_2":{
        "name": "Billy",
        "text" "",
    },
}]

Upvotes: 0

Views: 1625

Answers (2)

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

You can use the $pull operator to remove the sub-document whose text fields are empty -

var query = {};
var update = {
    $pull: {
        array_of_objects: {
            'object_1.text': '',
            'object_2.text': ''
        }
    }
};
var options = {
    multi: true
};

db.collection.update(query, update, options);

Upvotes: 0

Tiya Jose
Tiya Jose

Reputation: 1419

If you want to project all the fields that does not have an empty text string, use the following query.

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

MongoDB Playground

If you want to to project all the fields that does not have an empty text string and empty array, just add a $ne empty array check, use the following query:

MongoDB Playground

If you want to remove any document that has an empty text string, use an additional $match stage to remove documents with empty text string.

db.collection.aggregate([
  {
    $unwind: "$array_of_objects"
  },
  {
    $project: {
      array_of_objects: {
        $filter: {
          input: {
            $objectToArray: "$array_of_objects"
          },
          cond: {
            $and: [
              {
                $ne: [
                  "$$this.v.text",
                  ""
                ]
              },
              {
                $ne: [
                  "$$this.v",
                  []
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $match: {
      "array_of_objects.v.text": {
        $exists: true
      }
    }
  },
  {
    $project: {
      array_of_objects: {
        "$arrayToObject": "$array_of_objects"
      }
    }
  }
])

MongoDB Playground

Upvotes: 1

Related Questions