Search code examples
node.jsmongodbmongoose

Mongo DB - find() in array of arrays


I have such an data structure

{
    "level1": [
        {
            "id": 1,
            "level2": [
                [
                    {
                        "id": 1
                    },
                    {
                        "id": 2
                    },
                    {
                        "id": 5
                    }
                ],
                [
                    {
                        "id": 3
                    },
                    {
                        "id": 4
                    }
                ]
            ]
        }
    ]
}

How i can get element with id 3 via find() operator? level2 always has two arrays

I tried this - model.find({ 'level1.level2.$[i].$[j].id': 3 }), but its not working


Solution

  • Since level2 is an array of arrays, you can use:

    db.collection.find({
      "level1.level2": {$elemMatch: {$elemMatch: {id: 3}}}
    })
    

    to find the relevant document. See how it works on the playground example