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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.