How to use temporary variables in aggregations

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.

2 Likes