2

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.

1 Answer 1

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"
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.