Is there a way, in a MongoDB projection, to specify some new fields (but at the same time, retain fields that were input to the projection stage of the pipeline)? I'm not renaming any of the existing fields.
So if I start with a collection that has 'field1' and 'field2', and do the following projection:
{ $project: { field3: { $gt: ['$field1', 10] } } }
I want to end up with 'field1', 'field2', and 'field3' present as input to the next stage, or output from the aggregation framework.
I attempted to put the projection into exclusion mode by excluding _id, but that doesn't work.
where $project
needs to specify which fields to pass through, $addFields
will return all fields and add or replace specified fields.
{ $addFields: { field3: { $gt: ['$field1', 10] } } }
will achieve exactly what you want.
Please note, this feature was added in Mongo version 3.4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With