mongodb replace document code example

Example 1: mongodb replace string

db.mycollection.find({}).forEach((doc, index) => {
  doc.myStr = doc.myStr.replace('foo', 'bar');
  db.mycollection.save(doc);
});

Example 2: mongodb replace document

try {
   db.restaurant.replaceOne(
      { "name" : "Central Perk Cafe" },
      { "name" : "Central Pork Cafe", "Borough" : "Manhattan" }
   );
} catch (e){
   print(e);
}

Example 3: mongodb replace document

db.collection.replaceOne(
   ,
   ,
   {
     upsert: ,
     writeConcern: ,
     collation: ,
     hint:                    // Available starting in 4.2.1
   }
)

Tags:

Misc Example