Christian P
Christian P

Reputation: 12240

Multiple $elemMatch expressions for matching array values using $all in MongoDB?

In the answer to a question I found a interesting solution for searching array values using $elemMatch.

If we have the following documents in our collection:

{
    foo : [ { bar : "xy", baz : 1 },
            { bar : "a", baz : 10 } ]
},
{
    foo : [ { bar : "xy", baz : 5 },
            { bar : "b", baz : 50 } ]
}

The following query will match only the first document:

db.test.find({
    foo : { "$all" : [ { "$elemMatch" : { bar : "xy", baz : 1} }, { "$elemMatch" : { bar : "a", baz : 10 } } ] }
});

I tried it with several other examples and it really works. But the official documentation for $all operator doesn't say anything about combining these two queries.

Is this the intended behavior or a bug? Or is this just a problem that the documentation does not cover this use case?

Upvotes: 16

Views: 4855

Answers (1)

Sid
Sid

Reputation: 964

This is the intended behavior. The documentation doesn't cover this use case and we are working on it to make it better. Its difficult, however, to document every possible query combination.

Upvotes: 8

Related Questions