In this Chapter , we will learn about updating all the occurances of the data matching our query in a mongoDb database using node.js
Step - 1 : Including Packages
We will start by
requiring the package.
We are using the following package in our application :
var mongo = require('mongodb');
Step - 2 : Establish Connection
Now let's establish a connection between the mongoDb Database and our node.js application.
var new_db = "mongodb://localhost:27017/demo_db"
Step - 3 : Update all Occurances
updateMany() is the inbuilt method of mongodb which is used to search for the given query and update all its occurances.
Syntax
The syntax of the updateMany is :
db.collection("NAME_OF_THE_COLLECTION").updateMany(SEARCH_CONDITION , UPDATED_VALUE, (CALLBACK_FUNCTION) => {});
//updateMany-mongodb-nodejs.js
var mongo = require('mongodb');
var new_db = "mongodb://localhost:27017/demo_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();
});
});
D:\nj-learn-mongo>node updateMany-mongodb-nodejs.js
D:\nj-learn-mongo>node updateMany-mongodb-nodejs.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
}