Home > Back-end >  MongoDB Remove Empty Object from Array after aggregate function
MongoDB Remove Empty Object from Array after aggregate function

Time:11-07

The output of the db.name.aggregate() function gives output:

[{}, {"abc": "zyx"}, {}, "opk": "tyr"]

Actual output desired :

[{"abc": "zyx"}, "opk": "tyr"]

CodePudding user response:

Firstly, your output is not a valid array. It should be like this:

[{}, {"abc": "zyx"}, {}, {"opk": "tyr"}]

Now, to obtain your desired output, you can add the following $match stage, to your pipeline:

db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$gt": [
          {
            "$size": {
              "$objectToArray": "$$ROOT"
            }
          },
          0
        ]
      }
    }
  }
])

Here, we are converting the document to an array using $objectToArray, and then we check whether the size of that array is greater than 0. Only those documents are kept in the output.

Playground link.

CodePudding user response:

What if you data looks like this.

[
  {
    "arr": [
      {},
      {
        "abc": "zyx"
      },
      {},
      {
        "opk": "tyr"
      }
    ]
  }
]

The aggregation be like this to remove empty objects

db.collection.aggregate([
  {
    "$unwind": {
      "path": "$arr",
      
    }
  },
  {
    "$match": {
      arr: {
        "$ne": {}
      }
    }
  },
  {
    "$group": {
      _id: "$_id",
      arr: {
        $push: "$arr"
      }
    }
  }
])

Outputs

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "arr": [
      {
        "abc": "zyx"
      },
      {
        "opk": "tyr"
      }
    ]
  }
]

Demo@mongoplayground

https://mongoplayground.net/p/BjGxzlrlj6s

  • Related