MongoDB’s document is like a table’s row in RDBMS. to update document into the collection through updateOne() or updateMany() method.
Suppose, You have users collections that have 4 documents.
[
{
"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
"name" : "John",
"age" : 35
},
{
"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
"name" : "Rom",
"age" : 31
},
{
"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
"name" : "Mathew",
"age" : 32
},
{
"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
"name" : "Sachin",
"age" : 38
}
]
Update one document through updateOne() method
Firstly create the update_document.js file.
var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/";
var options = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
MongoClient.connect(url,options, function (err, connection_obj) {
try{
if (err) throw err;
var dbo = connection_obj.db("users_management");
var new_values={$set:{age:40}};
var where_condition={name:"John"}
dbo.collection("users").updateOne(where_condition,new_values, function(err, res) {
if (err) throw err;
console.log("1 document updated successfully");
//console.log(res);
console.log(res.result);
console.log(res.modifiedCount);
connection_obj.close();
});
}catch(err){
console.log("connection fails");
}
Now, run the update_document.js file.
node update_document.js
Output:-
1 document updated successfully
{ n: 1, nModified: 1, ok: 1 }
1
{ n: 1, nModified: 1, ok: 1 }
1
Update multiple documents through updateMany() method
Firstly create the update_documents.js file.
var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/";
var options = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
MongoClient.connect(url,options, function (err, connection_obj) {
try{
if (err) throw err;
var dbo = connection_obj.db("users_management");
var new_values={$set:{age:45}};
var where_condition={name:/o/}
dbo.collection("users").updateMany(where_condition,new_values, function(err, res) {
if (err) throw err;
console.log("documents updated successfully");
//console.log(res);
console.log(res.result);
console.log(res.modifiedCount);
connection_obj.close();
});
}catch(err){
console.log("connection fails");
}
Now, run the update_documents.js file.
node update_documents.js
Output:-
documents updated successfully
{ n: 2, nModified: 2, ok: 1 }
2
{ n: 2, nModified: 2, ok: 1 }
2