Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : find value in Array with multiple criteria

Tags:

mongodb

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

like image 930
JWally Avatar asked Aug 27 '12 20:08

JWally


People also ask

How do I search 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 find an element in an array 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.

How do I apply multiple conditions in MongoDB?

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.

How do you check if an array contains a value in MongoDB?

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>, ... } }


1 Answers

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.

like image 100
Louisa Avatar answered Oct 03 '22 22:10

Louisa