Skip to content

Instantly share code, notes, and snippets.

@sandeep-cs-dev
Forked from jasonk/README.md
Created March 13, 2023 20:52
Show Gist options
  • Save sandeep-cs-dev/202a2c4945f147f8d49f628636f10613 to your computer and use it in GitHub Desktop.
Save sandeep-cs-dev/202a2c4945f147f8d49f628636f10613 to your computer and use it in GitHub Desktop.
MongoDB Update Pipeline Tricks

Starting with MongoDB 4.2, you can use aggregation pipelines to update documents. Which leads to some really cool stuff.

For example, prior to this you could easily add sub-documents to an array using $addtoSet, and you could remove documents from an array using $pull, but you couldn't do both in the same operation, you had to send two separate update commands if you needed to remove some and add some.

With 4.2, now you can, because you can format your update as a pipeline, with multiple $set and $unset stages, which makes those things possible. However, since this is so new I had a really hard time finding examples of many of the things I wanted to do, so I started to collect some here for my reference (and yours).

See also:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment