Search code examples
mongodbaggregation

does the addfields aggregate field actually add fields to the collection?


I'm new to mongodb and aggregation. Specifically have a question about https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

I am trying to create a pipeline where I have a need to create temporary variables to carry values from one stage to the next. I believe the way you do this is to use the 'addFields' operator. Does the addFields operator add these temporary fields to the collection? If so, is there a way around it, as I don't want to store any derivative fields into the database. I have no use for the temporary inter-stage fields after the aggregation operation is complete.


Solution

  • As the $addfields documentation points out, The added fields only apply to the document in the context of the pipeline.

    1. That means the original document is not modified
    2. You can add $addfields at any point in the pipeline, deriving fields from the data in previous stages