Updating one or more documents

Command summary (discussed as follows):

  • db.<collection>.updateOne({<filter>},{<update>}[,{upsert:true}]);
  • db.<collection>.updateMany({<filter>},{<update>}[,{upsert:true}]);
  • db.<collection>.replaceOne({<filter>},{ // document }[,{upsert:true}]);

Both update*() and delete*() use a filter. The good news is that the filter uses exactly the same syntax as the find() command, mentioned previously. The difference between updateOne() and replaceOne() is that with the former you only need to supply the fields that need to be set or unset, whereas with the latter (for example, replaceOne()) you need to supply an entire replacement document. If the upsert parameter is set to true, a new document is inserted if the update ...

Get MongoDB 4 Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.