Chapter-3 Challenge Extension

Hi all,
I am trying to query all the documents that have scores in the result array ranging between 70 and 80. Here the criteria is all the scores in the result array must satisfy the condition(range 70-80).

{results:{$all:[{$elemMatch:{$gte:70, $lt:80}, {$elemMatch:{$gte:70, $lt:80}, {$elemMatch:{$gte:70, $lt:80}}]}}

I have tried querying the documents using the above logic but failed. If anyone knows the correct approach please let me know.

If I understood well, $elemMatch search in all array position, so you don’t need to use $all nether repeat query for each array position position.

Hope could help you understand how it works.

1 Like

Hi @sujeeth_09348

This is exactly what I am still looking for. A query to get "All the scores in the result array must satisfy the condition(range 70-80).". I asked the same here

If you find the solution, share with us please!

the filter: {results: {$in: [70, 71, 72, 73, 74, 75, 76, 77, 78, 79] } }
would give us answer.
looking for a way to put it in a more generic way. For eg if the range is 100 to 1000, it would be difficult for us to hard code all of the values.

{results: {$gte: 70, $lt: 80 } } would give us the answer . Reference :

That query returns wrong results, for example { “_id” : ObjectId(“5964e8e5f0df64e7bc2d7376”), “results” : [ 64, 82, 80 ] } because there is an element that is less than 80, in this case 64, and another greater/equal than 70, in this case 80 or 82, so both conditions are matched, but because of 2 different elements in the array. In the problem says that at least one of the elements must match BOTH conditions, here is where operator $elemenMatch comes to play the expressions would be ( attention to those that want to solve it by their own , by clicking on Result you will get the solution )



Thank you for correcting me. @Jesus_Javier_55985
What about {results: {$in: [70, 71, 72, 73, 74, 75, 76, 77, 78, 79] } }?

It works, it raises the same result, but, what if I tell you that the value must be between 1000 and 10,000 :slight_smile: ? As you can imagine it produces a very long query, or think in another possibility, we can have decimal values between 70 and 80, what if we had 75.01, or 75.2, or 75.342 ? you must consider all possible decimal values,it tends to infinite.