In databases like SQL Server, there’s the merge function for cases where users want that insert or update behavior. Mongo had this behavior since the beginning with the upsert operation (that has been enabled by setting the upsert option to true when using the update command - with $set
). The thing is that Mongo added in version 4.2 the $merge
operation. I’ve seen that it has something to do with the aggregation pipeline addition, which from my perspective is equivalent to creating a merge statement with custom conditions in SQL. If so, then what is the difference between the two?
CodePudding user response:
Similar to the catchphrase "aggregate() is the new find()", we now have "aggregate() is the new update()." The original update()
function is a performant and convenient way to update one or more records with a constant and relatively simple update expression. The pipeline version of update()
permits greater flexibility by enabling use of pipeline functions. But aggregate/$merge
-- especially on version >=4.4 where the target collection can be the same as the input -- affords the greatest degree of flexibility.