M001 Chapter 4 - Array operators and projection

Can someone clarify for me… I watched the lecture and the following command was identified as a query and a projection.

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

Where I am confused is in the prior lectures I was writing queries that were similiar.

db.companies.find({"$and": [{"$or": [{“founded_year”: 2004}, {“founded_month”: 10}]} , {"$or": [{“category_code”: “web”}, {“category_code”: “social”}]}]}).count()

db.listingsAndReviews.find({"$and": [{“accommodates”: {"$gt": 6}}, {“reviews”: {"$size": 50}}]}).pretty()

Is it standard that any query with multiple elements, the second one is the projection part? What is it about the elematch portion of the query that makes it the projection?

I want to know how to separate the parts from just looking at the query.

Hi @David_Thompson, I hear you, having an operator in the projection part of the query might not be very intuitive at first, but as mentioned in the official docs here,

“For fields that contain arrays, MongoDB provides the following projection operators for manipulating arrays: $elemMatch, slice, and .”

Hence $elemMatch in the first query is used as an operator for the selective projection of items in the embedded array inside each document. You can learn more at the docs link mentioned above.

For the record, the first object inside the find() is treated as the filter to extract documents from the collection and the second-object (if present) is used for projection of the fields in the returning documents.

In case of any doubts please feel free to reach out to me.

Thanks. Regards.
Sourabh Bagrecha,
Curriculum Services Engineer.

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