0

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

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

Actual output desired :

[{"abc": "zyx"}, "opk": "tyr"]
3
  • Are you sure is this the correct data returned? It is not the correct format for BSON. Commented Nov 7, 2022 at 4:54
  • If you show the full, or pertinent parts of the, aggregation pipeline, I'm confident someone will offer an option to produce the output you want. Commented Nov 7, 2022 at 4:57
  • This is a invalid array. Commented Nov 7, 2022 at 5:20

2 Answers 2

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.

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

Comments

1

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

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.