
- Node 與 MongoDB 教程
- Node 與 MongoDB - 主頁
- Node 與 MongoDB - 綜述
- Node 與 MongoDB - 環境設定
- Node 與 MongoDB 示例
- Node 與 MongoDB - 連線資料庫
- Node 與 MongoDB - 顯示資料庫
- Node 與 MongoDB - 刪除資料庫
- Node 與 MongoDB - 建立集合
- Node 與 MongoDB - 刪除集合
- Node 與 MongoDB - 顯示集合
- Node 與 MongoDB - 插入文件
- Node 與 MongoDB - 選擇文件
- Node 與 MongoDB - 更新文件
- Node 與 MongoDB - 刪除文件
- Node 與 MongoDB - 嵌入式文件
- Node 與 MongoDB - 限制記錄
- Node 與 MongoDB - 對記錄進行排序
- Node 與 MongoDB 有用資源
- Node 與 MongoDB - 快速指南
- Node 與 MongoDB - 有用資源
- Node 與 MongoDB - 討論
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.
廣告