- Reference >
- Operators >
- Aggregation Framework Operators >
- Pipeline Aggregation Operators >
- $project (aggregation)
$project (aggregation)¶
-
$project¶ Reshapes a document stream by renaming, adding, or removing fields. Also use
$projectto create computed values or sub-documents. Use$projectto:- Include fields from the original document.
- Insert computed fields.
- Rename fields.
- Create and populate fields that hold sub-documents.
Use
$projectto quickly select the fields that you want to include or exclude from the response. Consider the following aggregation framework operation.This operation includes the
titlefield and theauthorfield in the document that returns from the aggregation pipeline.Note
The
_idfield is always included by default. You may explicitly exclude_idas follows:Here, the projection excludes the
_idfield but includes thetitleandauthorfields.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
doctoredPageViewsrepresents the value of thepageViewsfield 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
$projectto rename fields. Consider the following example:This operation renames the
pageViewsfield topage_views, and renames thefoofield in theothersub-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
$projectto create and populate new sub-documents. Consider the following example that creates a new object-valued field namedstatsthat holds a number of values:This projection includes the
titlefield and places$projectinto “inclusive” mode. Then, it creates thestatsdocuments with the following fields:pvwhich includes and renames thepageViewsfrom the top level of the original documents.foowhich includes the value ofother.foofrom the original documents.dpvwhich is a computed field that adds 10 to the value of thepageViewsfield in the original document using the$addaggregation expression.