Projection: Only the Fields You Want

Full documents are long when you only need the titles. find takes a second argument called the projection. It lists the fields you want back:

db.movies.find({}, { _id: 0, title: 1 })

Output:

[
  { title: 'Inception' },
  { title: 'Interstellar' },
  { title: 'Parasite' },
  { title: 'Whiplash' },
  { title: 'La La Land' },
  { title: 'Okja' },
  { title: 'Dunkirk' },
  { title: 'First Man' }
]

In a projection, 1 means "include this field" and 0 means "leave it out". _id is special. It is included unless you leave it out with _id: 0. Every other field is left out unless you ask for it with 1.

The first argument is still the filter. It chooses the documents, and the projection chooses their fields:

db.movies.find(
  { director: "Christopher Nolan" },
  { _id: 0, title: 1, year: 1 }
)

Output:

[
  { title: 'Inception', year: 2010 },
  { title: 'Interstellar', year: 2014 },
  { title: 'Dunkirk', year: 2017 }
]

The filter kept three movies, and the projection kept two fields of each. Most queries in this course use a projection, so the results stay short and easy to read.

You cannot mix 1 and 0 in one projection. { title: 1, votes: 0 } gives an error. Either list the fields you want, or list the fields you do not want. _id: 0 is the one exception, and it works with either kind.

In the exercise, return the title and director of every movie.