Authors: @Jacqueline Osborn
Last Updated: 4/6/21
Projection is used for selecting specific fields to return. This is useful for when you have a collection with a very large amount of fields, but only need information from, say, three of them - by telling Mongo you only want those three, you reduce the amount of information sent over the API, helping with the response time. Below are some code examples of how you might effectively do this. Here's a link to MongoDB's excellent documentation (docs for operators) for more information.
If I have a user, and only want to return their name and age, I can do this:
db.users.find( {}, { name: 1 } );
// Returns
[
{ "_id": "1234", "name": "Kelley Chau" },
{ "_id": "1357", "name": "Kendall Hester" },
]
Note that _id is still returned here - that's because you have to specifically tell mongo if you don't want it included. So if you truly only wanted the name, you would do { name: 1, _id: 0 }.
To demonstrate how to do more advanced projection (and why is might be useful), we can take a Facebook user as an example. Say users is a MongoDB collection, that has many, many fields (ex. friends, likes, comments, name, birthday, etc.). However, when I mouse over someone's name on Facebook, I get a preview with just a few different pieces of information, like so:

If we are to simplify this down a bit for our purposes, if we had an API endpoint to fetch the data we need for this preview, we'd probably want these fields (assuming they exist in our users collection): name, recentFriend, mutualFriends, and _id, where name is a string, recentFriend is a user id, mutualFriends is an array of user ids, and _id is the id Mongo provides us with. We definitely don't want to return every single field associated with a user!
Given this, I may begin to set up my find() query like this (where I know Kelley's _id is 1234):
db.users.findOne(
{ _id: 1234 },
{ name: 1, recentFriend: 1, mutualFriends: 1 }
);
Here, it's important to note that the first set of brackets represents my actual query - this is where I specified I wanted to find user with _id equal to 1234.
This query might return something like this:
{
"name": "Kelley Chau",
"recentFriend": "5678", // _id for user "Ishaan Sehgal"
// ids for Prashant, Arpan, and all other mutual friends
"mutualFriends": ["91011", "121314", "4289243", // more ids for friends],
"_id": "1234"
}
This is a good start - but we can improve this! Since Kelley and I have a lot of mutual friends, but I only need the first two ids, we can tell mongo exactly that - to return the first two mutual friends. I can do this with the [$slice](https://docs.mongodb.com/manual/reference/operator/projection/slice/#:~:text=The %24slice projection operator specifies,return in the query result.&text=For information on limiting the,see %24slice aggregation operator instead.) projection operator, like so: