Update one document

updateone() method is used to update data in database. This method is a query object that specifies which document to update. It takes three parameters i.e. two query objects(one shows which object is to be updated, other shows the new data) and a callback function. We have to add atomic operators (such as $set, $unset, or $rename) with update if we do not give any operator it will give error.


var MongoClient = require('mongodb').MongoClient;
// Connection url
var url = "mongodb://127.0.0.1:27017/mydb";
// Connect using MongoClient
MongoClient.connect(url, function(err, Client) {
 if (err) throw err;
// Database Name mydb
 var db= Client.db('mydb');
// old value
 var oldvalue = { address: "jharkhand" };
// update value 
 var newvalues ={$set: { address: "mumbai" }};
// collection name “customers”
 db.collection("customers").updateOne(oldvalue, newvalues, 
function(err, result) {
   if (err) throw err;
   console.log("1 document updated");
   Client.close();
 });
});


In above example, ‘mydb’ is the database name in which ‘customers’ is a collection. Here in our example operator $set  is used to replace the value of a field with the new value.If we pass any field in update which is not present previously in our collection it will create that field.

Run Command 

C:\Users\Your Name>node updateone.js

Result 

1 document updated

Note: If the query finds more than one record, only the first occurrence is updated.


Update many document

updatemany() is a method which is used to update multiple documents in the database. It takes two query objects and a callback function. It will update all those documents which match our first query object.

// require mongodb
var MongoClient = require('mongodb').MongoClient;
// Connection url
var url = "mongodb://localhost:27017/mydb";
// Connect using MongoClient
MongoClient.connect(url, function(err, Client) {
 if (err) throw err;
// Database Name mydb
 var db= Client.db("mydb");
// old value
 var oldvalue = {name:'vishal singh'};
// new value
 var newvalues = {$set: {name: 'roopanjali',address:'bhopal'} };
// collection name “customers”
 db.collection("customers").updateMany(oldvalue, newvalues, function(err, res) {
   if (err) throw err;

    console.log(res.result.nModified + " document(s) updated");
   Client.close();
 });
});

The above example will update all those documents where ‘name’ is ‘vishal singh’. And set the new values (name: ‘roopanjali’, address:’bhopal’) there.

Run command 

C:\Users\Your Name>node updatemany.js

Result 

4 document(s) updated

Update document  using id  

We can also access ID in our node.js file by requiring ObjectId class present in mongodb module.

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

MongoClient.connect(url, function(err, Client) {
 console.log(url);
 
 if (err) throw err;
// database name mydb
 var db= Client.db("mydb");
 console.log(db);
 var oldvalue = { _id: ObjectId("5a45d69f97c79614c043b405") };

 var newvalues = {$set:{ name:"sandeep",address:"bhopal"} };
 db.collection("customers").updateMany(oldvalue, newvalues, function(err, res) {
   if (err) throw err;

    console.log(res.result.nModified + " document(s) updated");
   Client.close();
 });
});

In the above example we have created a variable ‘oldvalue’ which consists the following code

{ _id: ObjectId(“5a45d69f97c79614c043b405”) }, here in ObjectId instead of this pass your Object’s id string.

Run command 

C:\Users\Your Name>node update_id.js

Result 

1 document updated

Update document using $upsert

It is Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not update document when no match is found.

$upsert:- If set to true, creates a new document if no fields matches  in document

var MongoClient = require('mongodb').MongoClient;
// Connection url
var url = "mongodb://127.0.0.1:27017/mydb";
// Connect using MongoClient
MongoClient.connect(url, function(err, Client) {
 if (err) throw err;
// Database Name
 var db = Client.db('mydb');
 var myquery = { name: "shashi", address:"bhopal" };
 var newvalues = { name: "", city: "bhopal" };
var con= { upsert: true };
// collection Name customers
 db.collection("customers").update(myquery, newvalues, con , function(err, res) {
   if (err) throw err;
   console.log("1 document updated");
   Client.close();
 });
});

Run command 

C:\Users\Your Name>node update_id.js

Result 

1 document updated

Learn More-