- 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.
广告