15

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

3
  • Exact duplicate with stackoverflow.com/questions/6038818/… Commented Apr 9, 2012 at 8:28
  • thanks, i looked for similar questions but could not find one... Commented Apr 9, 2012 at 11:01
  • 2
    actually in your query you are using strings instead of numbers as well. Commented Apr 25, 2013 at 13:52

5 Answers 5

34

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

db.users.count({
    marks: {$elemMatch: {$gte: 20, $lt: 30}}
})
Sign up to request clarification or add additional context in comments.

Comments

7

Isn't it just this:

db.scores.count( { 'marks' : { '$gt' : min_value , '$lt' : max_value } } )

Which in your case would translate to:

db.scores.count( { 'marks' : { '$gt' : 20 , '$lt' : 30 } } )

Comments

2
db.scores.count(
   { marks: { $elemMatch: { $gte: 20, $lt: 30} } }
)

For more information refer https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

Comments

1

So assuming you had the following data in collection scores:

{ 'user_id' : 1, 'marks' : [ 10, 40 ] }
{ 'user_id' : 2, 'marks' : [ 5, 18 ] }
{ 'user_id' : 3, 'marks' : [ 15, 25 ] }
{ 'user_id' : 4, 'marks' : [ 22, 33 ] }

Then you would expect to filter user_ids 3 and 4, a count of 2.

The simplest way to run your query is to do:

db.scores.count({'marks':{$in: [20,21,22,23,24,25,26,27,28,29,30]}})

But not pretty...

1 Comment

yeah was thinking of not doing that. will accept this as there seems no other option
1

with $and you can also write

db.scores.count({$and: [{"price": {$lt: 30}}, {"price": {$gte: 20}}]})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.