”;
To update documents of a collection, you can use collection.updateOne() or collection.updateMany() methods to update one or multiple documents.
database.collection("sampleCollection").updateOne(query,updates, function(error, result) { if (error) throw error; console.log(''Document Updated''); }); database.collection("sampleCollection").updateMany(query,updates, function(error, result) { if (error) throw error; console.log(result.result.nModified + " document(s) updated"); });
Example
Try the following example to update a document in a mongodb collection −
Copy and paste the following example as mongodb_example.js −
const MongoClient = require(''mongodb'').MongoClient; // Prepare URL const url = "mongodb://localhost:27017/"; // make a connection to the database MongoClient.connect(url, function(error, client) { if (error) throw error; console.log("Connected!"); // Connect to the database const database = client.db(''myDb''); database.collection("sampleCollection").updateOne({First_Name:''Mahesh''}, { $set: { e_mail: ''[email protected]'' } }, function(error, result) { if (error) throw error; console.log(''Document Updated.''); }); // close the connection client.close(); });
Output
Execute the mysql_example.js script using node and verify the output.
node mongodb_example.js Connected! Document Updated.
Advertisements
”;