Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $project: Retain previous pipeline fields [duplicate]

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.

like image 761
BraedenP Avatar asked Dec 10 '13 14:12

BraedenP


1 Answers

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.

like image 183
Frazer Kirkman Avatar answered Nov 15 '22 23:11

Frazer Kirkman