2

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 }}} )
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Blitz
  • 59
  • 7

2 Answers2

2

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"] }
                }
            }
        }
    }
})
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
2

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"] }
        }
    }
});
Christian P
  • 12,032
  • 6
  • 60
  • 71