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
_id
property 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
fullName
property is a concatenation of thec_first
andc_last
sub-properties if thec_name
document property using the$concat
string operator and$string
literal operator. - The new
age
property is calculated from an existingc_birthdate
property, using$subtract
,$divide
, and$floor
arithmetic operators to calculate the age from the difference betweenc_birthdate
and today's date. - Since the
$project
stage 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"
}