OPTIONS

Limit Fields to Return from a Query

The projection specification limits the fields to return for all matching documents. The projection takes the form of a document with a list of fields for inclusion or exclusion from the result set. You can either specify the fields to include (e.g. { field: 1 }) or specify the fields to exclude (e.g. { field: 0 }).

Important

The _id field is, by default, included in the result set. To exclude the _id field from the result set, you need to specify in the projection document the exclusion of the _id field (i.e. { _id: 0 }).

You cannot combine inclusion and exclusion semantics in a single projection with the exception of the _id field.

This tutorial offers various query examples that limit the fields to return for all matching documents. The examples in this tutorial use a collection inventory and use the db.collection.find() method in the mongo shell. The db.collection.find() method returns a cursor to the retrieved documents. For examples on query selection criteria, see Query Documents.

Return All Fields in Matching Documents

If you specify no projection, the find() method returns all fields of all documents that match the query.

db.inventory.find( { type: 'food' } )

This operation will return all documents in the inventory collection where the value of the type field is 'food'. The returned documents contain all its fields.

Return the Specified Fields and the _id Field Only

A projection can explicitly include several fields. In the following operation, find() method returns all documents that match the query. In the result set, only the item and qty fields and, by default, the _id field return in the matching documents.

db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

Return Specified Fields Only

You can remove the _id field from the results by specifying its exclusion in the projection, as in the following example:

db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )

This operation returns all documents that match the query. In the result set, only the item and qty fields return in the matching documents.

Return All But the Excluded Field

To exclude a single field or group of fields you can use a projection in the following form:

db.inventory.find( { type: 'food' }, { type:0 } )

This operation returns all documents where the value of the type field is food. In the result set, the type field does not return in the matching documents.

With the exception of the _id field you cannot combine inclusion and exclusion statements in projection documents.

Projection for Array Fields

The $elemMatch and $slice projection operators are the only way to project portions of an array.

Tip

MongoDB does not support projections of portions of arrays except when using the $elemMatch and $slice projection operators.