So what’s the difference here?
I have to use aggregation pipeline because the real case contains other operators, so how can i use aggregation pipeline to achive the same result?
I had written a post about working with arrays but that’s not the case here, but looking (again) through the documentation it seems that within an aggregation pipeline $set is an alias for $addFields, in this case I guess it makes sense that it does not replace the existing field but adds a new element to the location specified.
In non-aggregation mode, it’s running so that it’ll replace what’s there.
If you wanted to do the same in the aggregation you need to add a new stage to the pipeline as far as I can tell to do this:
I managed to work around this by writing a 4 stage pipeline to fully emulate the behavior. The pseudo is like
collection.updateMany(query, [
{ $set: preset }, // Copy all involved fields of inner operators to a temporary field by walking through $set
{ $unset }, // Remove all objectlike fields of $set
{ $set }, // Actual operation
{ $unset: [tempKey] }, // Remove the temporary field in first stage
])
This was painful but works. Though i hope if we could do it better.