I have the following documents:
{_id : 1, numbers : [-1000, 1000]}
{_id : 2, numbers : [5]}
I'm trying to get a query that will find a document that has a value in the numbers array that is between -10 and 10 (in this case, _id : 2). However, when I try the following:
db.foo.find({numbers : $and : [{$gt : -10},{$lt : 10}]})
it returns all documents. Is this possible to do without map-reduce? Thanks, -JWW
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.
In MongoDB, we can apply the multiple conditions using the and operator. By applying the and operation we will select all the documents that satisfy all the condition expressions. We can use this operator in methods like find(), update() , etc as per the requirement.
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
You can use $elemMatch to check if an element in an array matches a specified match expression.
In this case, you can use it to get a document whose numbers array has an element that is between -10 and 10:
db.foo.find( { numbers : { $elemMatch : { $gt : -10 , $lt : 10 } } } );
This will just return the _id : 2 document.
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