2

MongoDB driver: 4.2.6, Mongoose: ^5.9.6

I want to unwind keyword properties:

[
 {
    "_id": null,
    "totalNumberOfData": 4,
    "data": [
        {
            "numberOfData": 2,
            "sentiment": "Good",
            "keyword": [
                "A",
                "B",
                "C"
            ]
        }
    ]
  }
]

I tried this, but it didn't work.

{
    $unwind: {
      path: "$data.keyword",
      preserveNullAndEmptyArrays: true,
    },
  },

How to unwind keyword array?

1 Answer 1

3

In general input to $unwind stage should be an array, Since you're doing data.keyword unwind is expected a field named data as an object with nested field named keyword as an array like :{data : keyword : []} & it's not able to find it that way which results in an empty array as output of aggregation. As data is also an array, you need to unwind it first, So double unwind is needed in your case :

db.collection.aggregate([
  {
    $unwind: {
      path: "$data",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $unwind: {
      path: "$data.keyword",
      preserveNullAndEmptyArrays: true
    }
  }
])

Test : mongoplayground

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

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.