Return Cos
Return Cos

Reputation: 77

Aggregating nested arrays in mongodb

I know I can use $in to match an element in an array, but what if the array is nested? Like so:

{
    "_id": ObjectId("somethingsomething"),
    "supermarkets": [
        {
            "groceries": [
                {
                    "groceryType": "banana",
                    "groceryStockDate": "12345678",
                    "groceryAmount": 12
                },
                {
                    "groceryType": "cabbage",
                    "groceryStockDate": "313512",
                    "groceryAmount": 53
                },
                {
                    "groceryType": "strawberry",
                    "groceryStockDate": "51362",
                    "groceryAmount": 52
                }
            ]
        },
        {
            "groceries": [
                {
                    "groceryType": "banana",
                    "groceryStockDate": "31321",
                    "groceryAmount": 52
                },
                {
                    "groceryType": "banana",
                    "groceryStockDate": "532451",
                    "groceryAmount": 73
                },
                {
                    "groceryType": "cucumber",
                    "groceryStockDate": "123",
                    "groceryAmount": 12
                }
            ]
        }
    ]
}

Here, I want to get every object with groceryType: banana, so the end result should be something like

[
    {
        "groceryType": "banana",
        "groceryStockDate": "12345678",
        "groceryAmount": 12
    },
    {
        "groceryType": "banana",
        "groceryStockDate": "31321",
        "groceryAmount": 52
    },
    {
        "groceryType": "banana",
        "groceryStockDate": "532451",
        "groceryAmount": 73
    }
]

I specifically want to do this with aggregate, as I need to pass this through more stages later.

Upvotes: 2

Views: 31

Answers (1)

Demo - https://mongoplayground.net/p/ayerR4qQMoI

Use $unwind on supermarkets and supermarkets.groceries to get individuals documents and use $match to filter the data and $project to get correct shape.

db.collection.aggregate({
  $unwind: "$supermarkets"
},
{
  $unwind: "$supermarkets.groceries"
},
{
  $match: {
    "supermarkets.groceries.groceryType": "banana"
  }
},
{
  $project: {
    _id: 0,
    groceries: "$supermarkets.groceries"
  }
})

Upvotes: 1

Related Questions