The projection stage takes a JSON document that can specify the inclusion of properties and/or the addition of new properties.
{"$project": {<projection spec>}}
Specifications
Specification | Description |
|---|---|
| Include this property in the projection |
| Add a new property to the projection |
Considerations
- Except for
_id, only properties that you specify for inclusion or add to the projection as new properties will be projected on to the next stage. - The
_idproperty is always included in the projection, even if you don't specify inclusion. - Existing properties cannot be overridden in a projection. If you wish to transform an existing property in a projection, it is recommended that you instead add a new property with a different name.
Examples
In the below example, a custom c_patient object is aggregated with a two stage pipeline in a script. The first stage is a $match that finds all patient records with c_gender: 'm'. That result set is then passed into the $project stage. The projection then specifies that c_name, and c_gender properties are included and that fullName and age are added as new properties.
- The new
fullNameproperty is a concatenation of thec_firstandc_lastsub-properties if thec_namedocument property using the$concatstring operator and$stringliteral operator. - The new
ageproperty is calculated from an existingc_birthdateproperty, using$subtract,$divide, and$floorarithmetic operators to calculate the age from the difference betweenc_birthdateand today's date. - Since the
$projectstage is the last stage in the pipeline, the result of the projection is returned as the response.
return org.objects.c_patients.aggregate()
.match({
c_gender: 'm'
})
.project({
c_name: 1,
fullName: {$concat: ['c_name.c_first', {$string: ' '}, 'c_name.c_last']},
c_gender: 1,
age: { $floor: { $divide: [{ $subtract:[new Date(), 'c_birthdate']}, (365 * 24*60*60*1000)]}}
})
.toList();{
"data": [
{
"_id": "59495fb2514ef1010000598b",
"age": 38,
"c_gender": "m",
"c_name": {
"c_first": "John",
"c_last": "Smith"
},
"fullName": "John Smith"
},
{
"_id": "59495fd7514ef1010000598f",
"age": 48,
"c_gender": "m",
"c_name": {
"c_first": "Charles",
"c_last": "Jones"
},
"fullName": "Charles Jones"
},
{
"_id": "59496012cfc40501006c10d2",
"age": 43,
"c_gender": "m",
"c_name": {
"c_first": "Richard",
"c_last": "Roberts"
},
"fullName": "Richard Roberts"
}
],
"hasMore": false,
"object": "list"
}