Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 260
Christian P Avatar asked Mar 22 '12 14:03

Christian P


People also ask

How do you match an array element in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

What does $all do in MongoDB?

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

How do I test multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

How do I query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

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.

like image 93
Sid Avatar answered Sep 20 '22 08:09

Sid