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 }}} )

2 Answers 2

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

Comments

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"] }
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.