I have a schema similar to
{
'user_id' : 1,
'marks' : [10, 40]
}
I want to find the number of users who have scored marks between 20 and 30 at least once.
I tried the following query
db.users.count({
'marks' : {$gte: '20', $lt: '30'}
})
But this also included those with marks more than 30 ...
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.
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.
MongoDB provides different types of comparison operators and greater than equals to operator($gte) is one of them. This operator is used to select those documents where the value of the field is greater than equals to(>=) the given value. You can use this operator in methods (like, find(), update(), etc.)
Use $elemMatch
to constrain both parts of the range query to the same marks
element:
db.users.count({
marks: {$elemMatch: {$gte: 20, $lt: 30}}
})
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