How to use temporary variables in aggregations

How can I define and use temporary variables in an aggregation for usage in the different stages?
Sure I can define a new field like this

	$set: {
		isLastReceiveTimeBack: "$isLastReceiveTime" 

and remove it afterwards with an $unset stage but this seems to me not that handy.

Hello @Frank_Numrich1,

It would be helpful if you share the actual use case, might be there some alternative approach available instead of creating an extra variable and removing it?

Alternative to $unset you can use the $$REMOVE operator to remove the property from any projection stage.

{ $set: { isLastReceiveTimeBack: "$$REMOVE" } }
//You can do the same in the $addFields stage
1 Like

In some cases, you may use $let.

But I like to use $set this way I can see my temp. variables in intermediate results. What I do is the I put them all in a top field named _tmp. This way they are all grouped together and a single $unset remove them all.

See Update all documents in a collection based on a property which is under a dynamic field - #4 by steevej, Sorting based on dynamic filed value - #5 by steevej and Updating nested array fields with values from another field in the nested document - #11 by steevej for how I use that.


Hi @turivishal ,

in fact the reason or use case is described in this post: Aggregations: Use $cond without an else clause

I want to use a condition ($cond) without an else clause to update a field in case the if-condition resolves to true. If it resolves to false the field should stay untouched. Since I found no other/better way so far I store the origin value into a temp variable, execute the else clause i set the field to the stored origin value.

However, this is rather cumbersome …

And thanks for the hint regarding $$REMOVE.

1 Like

Hi @steevej ,

indeed $let would be an option here, thanks for the hint.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.