Projections in MongoDB
- Projections in mongodb allows us to get only the fields that are needed rather than the entire document. This makes it easier for the cursor to traverse and even for us as we do not see unnecessary fields
- Projections are listed after the query
db.collection_name.find(<query>, <projections>)
- The projections itself is an object that will store the fields that are to be selected or ignore.
- The fields you want to include in the subset is written as
db.collection_name.find(<query>, {"field1": 1, "field2": 1})
- The fields that need to be ignored in the subset can be written as
db.collection_name.find(<query>, {"field3": 0, "field4": 0})
- We cannot specify both at once i.e. the fields we want to include and the fields we don't want to include cannot be specified in the same projection query
- The only time we can use both 1s and 0s is when you are explicitly asking to exclude the
_id
field as it will be included otherwise.
For example, let's look at the documents in the sample_training.grades
collections
$elemMatch
is an array operator that can look for fields in the array
Let's say we want to find out how many students took the course 431 and scored more than 85%.
db.grades.find({"class_id": 431, "scores": {"$elemMatch": {"score": {"$gt": 85}}}}).count()
Now let's find all the students who received an extra credit for any course
Lab
- How many companies in the sample_training.companies collection have offices in the city of Seattle?
db.companies.find({"offices": {"$elemMatch": {"city": "Seattle"}}}).count()