Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongo db querying array values with greater and less than

Tags:

arrays

mongodb

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

like image 521
Rishabh Avatar asked Apr 09 '12 06:04

Rishabh


People also ask

How do you match an array element in MongoDB?

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.

How do I query an array of objects 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 greater than in MongoDB?

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.)


1 Answers

Use $elemMatch to constrain both parts of the range query to the same marks element:

db.users.count({
    marks: {$elemMatch: {$gte: 20, $lt: 30}}
})
like image 159
JohnnyHK Avatar answered Oct 18 '22 17:10

JohnnyHK