In this part of the mongodb operations using node.js tutorial series , we will learn about updating all
the occurrences of data matching a certain criteria from a mongodb collection
using node.js
.
We will start by including mongodb
npm package as shown below :
var mongo = require('mongodb');
Establish a connection between the mongoDb database and our node.js app using the following :
var new_db = "mongodb://localhost:27017/demo_db"
updateMany()
is an inbuilt method of mongodb
which is used to update all the
occurrences of data obtained using the search query.
The syntax of updateMany()
function is given below :
db.collection("NAME_OF_THE_COLLECTION").updateMany(SEARCH_CONDITION , UPDATED_VALUE, (CALLBACK_FUNCTION) => {});
//update-many.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_db"
//connecting to the db
mongo.connect(new_db ,(error , db) => {
if (error){
throw error;
}
//query store the search condition
var query = { age : {$gt : "22" } };
//data stores the updated value
var data = { $set : {age : "above 22" } }
//CREATING A COLLECTION IN MONGODB USING NODE.JS
db.collection("details").updateMany(query , data, (err , collection) => {
if(err) throw err;
console.log(collection.result.nModified + " Record(s) updated successfully"); //It will console the number of rows updated
console.log(collection);
db.close();
});
});
>node update-many.js
3 Record(s) updated successfully
{ result:
{
ok: 1,
n: 3,
nModified: 3
},
connection: null,
message: undefined,
modifiedCount: 3,
upsertedId: null,
upsertedCount: 0,
matchedCount: 3
}
In this article we learned about
monogdb
npm package in your app. updateMany()
operation in mongodb using node.js