Update Into MongoDB


Update document into collection at MongoDB using Node.js.  You can update the document in MongoDB using updateOne(). If the query finds more than one record, only the first occurrence is updated.

Topics Covered 

  • Update One – Update single Document from Collection
  • Update One – Update Only Specific Fields in a single Document from Collection
  • Update Many – Update all Documents that match the query from Collection

Update One – Update single Document from Collection

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var myquery = { address: "Valley 345" };
  var newvalues = { name: "Mickey", address: "Canyon 123" };
  db.collection("customers").updateOne(myquery, newvalues, function(err, res) {
    if (err) throw err;
    console.log("1 document updated");
    db.close();
  });
});

Update One – Update Only Specific Fields in a single Document from Collection

Learn More-