- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $project (aggregation)
$project (aggregation)¶
-
$project
¶ Reshapes a document stream by renaming, adding, or removing fields. Also use
$project
to create computed values or sub-documents. Use$project
to:- Include fields from the original document.
- Insert computed fields.
- Rename fields.
- Create and populate fields that hold sub-documents.
Use
$project
to quickly select the fields that you want to include or exclude from the response. Consider the following aggregation framework operation.This operation includes the
title
field and theauthor
field in the document that returns from the aggregation pipeline.Note
The
_id
field is always included by default. You may explicitly exclude_id
as follows:Here, the projection excludes the
_id
field but includes thetitle
andauthor
fields.Projections can also add computed fields to the document stream passing through the pipeline. A computed field can use any of the expression operators. Consider the following example:
Here, the field
doctoredPageViews
represents the value of thepageViews
field after adding 10 to the original field using the$add
.Note
You must enclose the expression that defines the computed field in braces, so that the expression is a valid object.
You may also use
$project
to rename fields. Consider the following example:This operation renames the
pageViews
field topage_views
, and renames thefoo
field in theother
sub-document as the top-level fieldbar
. The field references used for renaming fields are direct expressions and do not use an operator or surrounding braces. All aggregation field references can use dotted paths to refer to fields in nested documents.Finally, you can use the
$project
to create and populate new sub-documents. Consider the following example that creates a new object-valued field namedstats
that holds a number of values:This projection includes the
title
field and places$project
into “inclusive” mode. Then, it creates thestats
documents with the following fields:pv
which includes and renames thepageViews
from the top level of the original documents.foo
which includes the value ofother.foo
from the original documents.dpv
which is a computed field that adds 10 to the value of thepageViews
field in the original document using the$add
aggregation expression.