Confused about the Chapter 4 Lecture: Array Operators and Projection, the query to find all students in class 431 grade higher than 85

the query in the lecture written as following:
db.grades.find({ “class_id”: 431 }, { “scores”: { “$elemMatch”: { “score”: { “$gt”: 85 } } } }).pretty()
but according the question we should write it this way:
db.grades.find({class_id:431, scores: { $elemMatch: {score:{$gte:85} }}}).pretty()
Am I understanding this correctly ?

You are correct.

@SourabhBagrecha, please take a look at it.

Hi @Junlei_Li, welcome to the community.
Thank you for pointing this out, but your suggested query is not appropriate for the kind results that we are trying to achieve here.
Please note that the find command has the following syntax:

db.grades.find({<---query--->}, {<---projection--->})

The objective of the first $elemMatch question in the lecture was to:

Find all the documents in the grades collection which have the {class_id: 431}, it doesn’t matter whether those students have scored 85 or not, but at the time of projection only those scores that are greater than 85 should be displayed.

And the query mentioned below is perfect for this scenario:

db.grades.find({ “class_id”: 431 }, { “scores”: { “$elemMatch”: { “score”: { “$gt”: 85 } } } }).pretty()

However, if the question was:

Find all the documents in the grades collection where students have scored more than 85 in at least one of their subjects, and it is okay to display other scores that are less than 85.

Then your query would be considered as appropriate:

db.grades.find({class_id:431, scores: { $elemMatch: {score:{$gte:85} }}}).pretty()

Lear more about how $elemMatch works inside projection.

@steevej thanks for flagging this, but I think the query mentioned in the lecture is correct and apt for the scenario mentioned, let me know if I am missing something.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

2 Likes

Thanks for link.

You are totally right. I am the one who missed something. I use the syntax

db.CollectionName.find( my_query ).projection( my_projection )

to accomplish this. So I fumbled.

Saru mo ki kara ochiru

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.