Defining a projection

The projection delineates which fields within a document are included in or excluded from the final output. In MongoDB, the projection takes the form of a JSON expression consisting of key:value pairs. The key is the name of the field, and the value is either 1 or 0. Fields to be included are assigned 1. Fields to be excluded are assigned 0. By default, all fields are included.

For this illustration, assume a collection products where each document has the fields _id, sku, title, price, and description. We start by searching for all documents that have Cookies in the title, and only want to see sku, title, and price. Your initial thought might be to issue a find() where the projection is; {sku:1,title:1,price:1}:

Get MongoDB 4 Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.