ian
ian

Reputation: 53

Mongodb $unwind array of arrays in an array

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?

Upvotes: 2

Views: 2405

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17935

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

Upvotes: 3

Related Questions