Node.js MongoDB 更新文档
更新文档
您可以使用 updateOne() 方法更新 MongoDB 中的文档。
updateOne() 方法的第一个参数是定义要更新哪个文档的查询对象。
注意:如果查询找到多条记录,则只更新第一次记录。第二个参数是定义文档新值的对象。
实例
Update the document with the address "Valley 345" to name="Mickey" and address="Canyon 123"
将 address 为 "Valley 345" 的文档更新为name=“Mickey”和address=“Canyon 123”:
var MongoClient = require('mongodb').MongoClient;var url = "mongodb://127.0.0.1:27017/";MongoClient.connect(url, function(err, db) {if (err) throw err;var dbo = db.db("mydb");var myquery = { address: "Valley 345" };var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {if (err) throw err;console.log("1 document updated");db.close();});});
将上述代码保存在名为 "demo_update_one.js" 的文件中,然后运行该文件:
运行 "demo_update_one.js"
C:\Users\ Your Name >node demo_update_one.js
结果如下:
1 document updated
更新指定字段
使用 $set 运算符时,仅更新指定的字段:
实例
将 address 从 "Valley 345" 更新为 "Canyon 123":
...var myquery = { address: "Valley 345" };var newvalues = { <strong>$set: { address: "Canyon 123" }</strong> };dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {...
更新多个文档
要更新符合查询条件的 所有 文档,请使用 updateMany() 方法。
实例
更新 name 以字母 "S"开头的所有文档:
var MongoClient = require('mongodb').MongoClient;var url = "mongodb://127.0.0.1:27017/";MongoClient.connect(url, function(err, db) {if (err) throw err;var dbo = db.db("mydb");var myquery = { address: /^S/ };var newvalues = {$set: {name: "Minnie"} };dbo.collection("customers").updateMany(myquery, newvalues, function(err, res) {if (err) throw err;console.log(res.result.nModified + " document(s) updated");db.close();});});
将上述代码保存在名为 "demo_update_many.js" 的文件中,然后运行该文件:
运行 "demo_update_many.js"
C:\Users\ Your Name >node demo_update_many.js
结果如下:
2 document(s) updated
结果对象
updateOne() 和 updateMany() 方法返回一个对象,其中包含该执行对数据库的影响的信息。
大多数信息对于理解来说并不重要,但对象中有一个对象称为 "result",它告诉我们执行是否正常,以及有多少文档受到影响。结果对象如下所示:
{ n: 1, nModified: 2, ok: 1 }
您可以使用此对象返回已更新文档的数量:
实例
返回更新文档的数量:
console.log(res.result.nModified);
结果如下:
2