skip to Main Content

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

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

Actual output desired :

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search