0

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

2 Answers 2

1

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

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

Comments

0

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);

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.