Node 與 MongoDB - 更新文件



要更新集合的文件,可以使用collection.updateOne()collection.updateMany()方法更新一個或多個文件。

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");
});

示例

嘗試以下示例,以更新 mongodb 集合中的文件 -

複製並貼上以下示例為 mongodb_example.js -

const MongoClient = require('mongodb').MongoClient;
// Prepare URL
const url = "mongodb://: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: 'maheshparashar@gmail.com' } }, function(error, result) {
      if (error) throw error;
      console.log('Document Updated.');
   });   
   // close the connection
   client.close();
});

輸出

使用 node 執行 mysql_example.js 指令碼並驗證輸出。

node mongodb_example.js
Connected!
Document Updated.
廣告