Overview
您可以使用更新和替换操作来修改 MongoDB 集合中的文档。更新操作可以修改文档的字段和值,同时保持其他字段和值不变。替换操作使用指定字段和值替换现有文档中的所有字段和值,同时保持 _id 字段值不变。
Node.js 驱动程序提供以下用于更改文档的方法:
updateOne()updateMany()replaceOne()
要学习;了解如何替换文档,请参阅替换文档指南。
提示
互动实验室
本页包括一个简短的交互式实验室,演示了如何使用 updateMany() 方法修改数据。无需安装 MongoDB 或代码编辑器,即可直接在浏览器窗口中完成此实验。
要启动实验室,请单击页面顶部的 Open Interactive Tutorial 按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 (⛶)。
Update Documents
如需对一个或多个文档执行更新,请创建更新文档,指定更新操作符(要执行的更新类型)以及描述更改的字段和值。更新文档使用以下格式:
{ <update operator>: { <field> : { ... }, <field> : { } }, <update operator>: { ... }}更新文档的顶层包含以下一个或多个更新运算符:
$set:用指定值替换字段的值$inc:递增或递减字段值$rename:重命名字段$unset:删除字段$mul:将字段值乘以指定的数值
有关更新操作符及其用法的完整列表,请参阅 MongoDB Server 手册。
更新操作符只适用于更新文档中与之关联的字段。
注意
更新操作中的聚合管道
如果您使用的是 MongoDB 4.2或更高版本,则可以在更新操作中使用由聚合阶段子集组成的聚合管道。 有关 MongoDB 在更新操作中使用的聚合管道中支持的聚合阶段的更多信息,请参阅有关使用聚合管道构建更新的教程。
例子
以 myDB.items 集合中的文档为例,其中包含描述待售商品、价格和可用数量的字段:
{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 7,}如果应用 $set 更新运算符,并为 quantity 添加新值,则可以使用以下更新文档:
const myDB = client.db("myDB");const myColl = myDB.collection("items");
const filter = { _id: 465 };
// update the value of the 'quantity' field to 5const updateDocument = { $set: { quantity: 5, },};const result = await myColl.updateOne(filter, updateDocument);更新后的文档类似以下内容,其中 quantity 字段的值已更新,而所有其他值则保持不变:
{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 5,}如果更新操作无法与集合中的任何文档匹配,则不会进行任何更改。更新操作可以配置为执行更新或插入,尝试执行更新,但如果没有匹配的文档,则会插入具有指定字段和值的新文档。
您不能修改文档的_id字段,也不能将字段更改为违反唯一索引约束的值。 有关唯一索引的更多信息,请参阅 MongoDB Server 手册。
updateOne() 示例:完整文件
注意
设置示例
该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。
此示例使用 $set更新操作符符指定文档字段的更新值。有关更新操作符的更多信息,请参阅MongoDB更新操作符参考文档。
以下代码是一个完整的独立运行文件,用于执行更新一个操作:
// Update a document
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies");
// Create a filter for movies with the title "Random Harvest" const filter = { title: "Random Harvest" };
/* Set the upsert option to insert a document if no documents match the filter */ const options = { upsert: true };
// Specify the update to set a value for the plot field const updateDoc = { $set: { plot: `A harvest of random numbers, such as: ${Math.random()}` }, };
// Update the first document that matches the filter const result = await movies.updateOne(filter, updateDoc, options); // Print the number of matching and modified documents console.log( `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, ); } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown errorsrun().catch(console.dir);// Update a document
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>";
const client = new MongoClient(uri);
// Define the Movie interfaceinterface Movie { plot: string; title: string;}
async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection<Movie>("movies");
/* Update a document that has the title "Random Harvest" to have a plot field with the specified value */ const result = await movies.updateOne( { title: "Random Harvest" }, { $set: { plot: `A harvest of random numbers, such as: ${Math.random()}`, }, }, /* Set the upsert option to insert a document if no documents match the filter */ { upsert: true } );
// Print the number of matching and modified documents console.log( `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)` ); } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown errorsrun().catch(console.dir);运行上述示例将产生以下输出:
1 document(s) matched the filter, updated 1 document(s)updateMany() 示例:完整文件
注意
设置示例
该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。
以下代码是一个完整的独立运行文件,用于执行更新多次操作:
/* Update multiple documents */
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() { try { // Get the "movies" collection in the "sample_mflix" database const database = client.db("sample_mflix"); const movies = database.collection("movies");
// Create a filter to update all movies with a 'G' rating const filter = { rated: "G" };
// Create an update document specifying the change to make const updateDoc = { $set: { random_review: `After viewing I am ${ 100 * Math.random() }% more satisfied with life.`, }, }; // Update the documents that match the specified filter const result = await movies.updateMany(filter, updateDoc); console.log(`Updated ${result.modifiedCount} documents`); } finally { // Close the database connection on completion or error await client.close(); }}run().catch(console.dir);/* Update multiple documents */
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>";
const client = new MongoClient(uri);
enum Rating { G = "G", PG = "PG", PG_13 = "PG-13", R = "R", NR = "NOT RATED",}
// Create a Movie interfaceinterface Movie { rated: Rating; random_review?: string;}
async function run() { try { // Get the "movies" collection in the "sample_mflix" database const database = client.db("sample_mflix"); const movies = database.collection<Movie>("movies");
// Update all documents that match the specified filter const result = await movies.updateMany( { rated: Rating.G }, { $set: { random_review: `After viewing I am ${ 100 * Math.random() }% more satisfied with life.`, }, } ); console.log(`Updated ${result.modifiedCount} documents`); } finally { // Close the database connection on completion or error await client.close(); }}run().catch(console.dir);运行前面的示例,您会看到如下输出:
Updated 477 documentsAPI 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: