MongoDB: find a value in an array with multiple criteria

I have the following documents:

{_id : 1, numbers : [-1000, 1000]} {_id : 2, numbers : [5]} 

I am trying to get a query that will find a document that has a value in an array of numbers that is between -10 and 10 (in this case, _id: 2). However, when I try to do the following:

 db.foo.find({numbers : $and : [{$gt : -10},{$lt : 10}]}) 

he returns all the documents. Is it possible to do without reducing the map? Thanks, -JWW

+7
source share
1 answer

You can use $ elemMatch to check if the element in the array matches the specified matching expression.

In this case, you can use it to get a document whose array of numbers has an element from -10 to 10:

  db.foo.find( { numbers : { $elemMatch : { $gt : -10 , $lt : 10 } } } ); 

This will simply return the _id: 2 document.

+7
source

All Articles