Challenge Question Confusion

Hello,

I realized that we had to use the $elemMatch operator to find the correct answer, but I was thinking of another way to find it. I thought, what if I saved the count of how many documents have a value that matches the criteria per array index position. In this case, results only has 3 positions: 0,1,2. So if I simply found the total of each document where each index position of the array meets the criteria of being greater than or equal to 70 and less than 80 I should get the correct answer right?

So I saved them in three different values, added them up and got 762. This is assuming that the question is asking to find how many documents hold a value in the results array where at least ONE of the values is both greater than or equal to 70 AND less than 80.

Why does my solution not work?

Attached is a screenshot that shows what I did: image

Also, how can I query a specific index of an array? I tried querying specific index positions to try to figure out why I am wrong and I got these results: image

Thank you! :smiley:

Hi @Raul_26412,

First of all good question and I’m so happy to see the efforts you have put into it :slight_smile:

Now, let’s see why your approach is not giving the desired results.

Let’s say I have this document in my scores collection.

{  "_id": ObjectId("5964e8e5f0df64e7bc2d737c"), "results": [72,77,80 ]}

Let’s query for the 0th index :

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

This will return a positive match because 72 is {$gte:70,$lt:80}}.

Let’s query for the 1st index :

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

This will return a positive match because 77 is {$gte:70,$lt:80}}.

Do you see what’s happening here :slight_smile: ?

We are counting the same document twice and that’s why your query is returning higher number of matches.

You can query a specific index of an array element by the array Index Position. This is what you just did in the above example.

Now, the reason why you got empty array in the output is because the syntax is incorrect here.

I believe what you wanted to do here is that you wanted to project only the 0th element of the results array.

There are several ways in which you can do it. I am going to discuss one of those using the $slice operator.

db.scores.find({"results":{$gt:0}},{"results":{$slice:[0,1]},"_id":0})

42%20PM

Here, I have passed two parameter to the $slice operator. The first one is the skip value, which tells the number of values to skip from beginning and the second values is the limit values which tells the number of elements to project.

Hope it helps !

If you still have any query, please feel free to get back to us.

Happy Learning :slight_smile:

Thanks,
Shubham Ranjan
Curriculum Support Engineer

2 Likes

Oh my yes, thank you! Using the $slice operator was exactly what I was looking for!