Update 操作是指修改 MongoDB 集合中文档中一个或多个字段的值。Node.js 的 mongodb 驱动程序定义了 updateOne() 和 updateMany() 方法。updateOne() 方法用于修改单个文档,而 updateMany() 方法对多个文档执行更新。
updateOne() 方法的语法如下 -
collection.updateOne(query, values);
查询参数有助于查找要更新的所需文档。values 参数包含要修改文档的键值对。updateMany() 方法遵循相同的语法,不同之处在于查询从集合中返回多个文档。
updateOne()
以下示例更改 ProductID=3 的文档的价格。$set运算符为价格字段分配一个新值。
const {MongoClient} = require('mongodb');
async function main(){
const uri = "mongodb://localhost:27017/";
const client = new MongoClient(uri);
try {
await client.connect();
await sortdocs(client, "mydb", "products");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
async function sortdocs(client, dbname, colname){
var qry = { ProductID: 3 };
var vals = { $set: { Name: "Router", price: 2750 } };
const result = await client.db(dbname).collection(colname).updateOne(qry, vals);
console.log("Document updated");
}
要验证文档是否已更新,请使用 Mongosh shell 并输入以下命令 -
> use mydb
< switched to db mydb
> db.products.find({"ProductID":3})
{
_id: ObjectId("6580964f20f979d2e9a72ae9"),
ProductID: 3,
Name: 'Router',
price: 2750
}
updateMany()
假设产品集合具有以下名称以“er”结尾的文档。

以下 sortdocs() 函数将上述所有产品的价格增加 125 卢比。我们使用了 $inc 运算符。
例
async function sortdocs(client, dbname, colname){
var qry = {Name: /er$/};
var vals = { $inc: { price: 125 } };
const result = await client.db(dbname).collection(colname).updateMany(qry, vals);
console.log("Documents updated");
}
输出