MongoDB : find documents having 2 values in Array conforming to multiple criteria
arrays, mongodb, mongodb-query
Solution
You've got the right idea, but the `$and` needs to be at the top level of your conditions object:
db.Collection.find({$and: [
{arr: {$elemMatch: {$gte: 4, $lte: 9}}},
{arr: {$elemMatch: {$gte: 45, $lte: 55}}}
]})
If you also want to ensure that these are the only two elements, then you can add another term to the `$and` array to check that:
db.Collection.find({$and: [
{arr: {$elemMatch: {$gte: 4, $lte: 9}}},
{arr: {$elemMatch: {$gte: 45, $lte: 55}}},
{'arr.2': {$exists: false}}
]})
Problem
Suppose, we have documents: ``` {_id : 1, arr : [5,50]} {_id : 2, arr : [11,53]} ``` The goal is to find documents which have 2 values in array, one has to be in range(4,9), the second in range(45,55). In this case, only document with _id : 1 should return. Tried this: `db.Collection.find({arr : {$elemMatch : {$gte : 4, $lte : 9}}})` - returns the first document `db.Collection.find({arr : {$elemMatch : {$gte : 45, $lte : 55}}})` - returns both How to combine these criteria together? ``` db.Collection.find({arr : {$and : [{$elemMatch : {$gte : 4, $lte : 9}}, {$elemMatch : {$gte : 45, $lte : 55}}]}}) ``` returns : error: { "$err" : "invalid operator: $and", "code" : 10068 }