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?
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.
The $all operator selects the documents where the value of a field is an array that contains all the specified elements.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With