Chapter 3 Challenge Problem - using $gte/$lt inside $and, which is inside an $elemMatch?

Hi, I was solving the challenge problem in chapter 3, and I came up with this query:

db.scores.find({ results: { $elemMatch: { $and: [ {$gte: 70}, {$lt: 80} ] }} }).count()

and this encounter an error like this:

uncaught exception: Error: count failed: {

  •    "operationTime" : Timestamp(1598001566, 1),*
    
  •    "ok" : 0,*
    
  •    "errmsg" : "unknown top level operator: $gte",*
    
  •    "code" : 2,*
    
  •    "codeName" : "BadValue",*
    
  •    "$clusterTime" : {*
    
  •            "clusterTime" : Timestamp(1598001566, 1),*
    
  •            "signature" : {*
    
  •                    "hash" : BinData(0,"rle4s8b/fyU0sU4OZURhl2EkL3E="),*
    
  •                    "keyId" : NumberLong("6829321948548300802")*
    
  •            }*
    
  •    }*
    

} :

but without using the $and operator like the below query, the query works fine:

db.scores.find({ results: { $elemMatch: { $gte: 70, $lt: 80 } } }).count()

This is fine with this case, but what about if i need to find a value that less than 20 OR greater than 80? In this case, $or operator must be use, but the $gte/$lt operator cannot be used inside a $or, which is inside a $elemMatch! How to query in such case? Thanks!

You can use $and,$or with elemMatch

Try this.Not exact solution for your query but you need to modify as per your requirement

db.scores.find({ $and: [{ “results” : { $elemMatch : { $gte: 70, $lt : 80}} }]}).count()

Hi @Isaac_wu,

Please review our documentation and you would be able to figure out what went wrong with your query.

$elemMatch (query)

Hope it helps!

If something is not clear then please feel free to reach out to us.

~ Shubham