Blitz
Blitz

Reputation: 59

mongodb query nested structure

How can I query this nested json structure in order to find documents that contain "A"?

"categories":[{"id":12,"values":[["A","B","C"]]},{"id":17,"values":[["D","E","F"]]}]

So far, I only managed to get to the id value with

db.coll.find( {categories: { $elemMatch: { id: 12 }}} )

Upvotes: 2

Views: 1120

Answers (2)

Christian P
Christian P

Reputation: 12240

Although Neil's answer will work, you can do it with only two $elemMatch operators, instead of three to make it simpler.

You can use dot notation to get to the values property and then you can use nested $elemMatch operators to check the nested array value:

db.coll.find({
    "categories.values" : { 
        $elemMatch : { 
            $elemMatch : { $in : ["A", "B"] }
        }
    }
});

Upvotes: 2

Neil Lunn
Neil Lunn

Reputation: 151230

You need to nest the $elemMatch operators to match the nested levels of your arrays to match the element:

db.coll.find({
    "categories": { 
        "$elemMatch": { 
            "values": { 
                "$elemMatch": {
                    "$elemMatch": { "$in": ["A"] }
                }
            }
        }
    }
})

Upvotes: 2

Related Questions