Overview概述
You can modify documents in a MongoDB collection by using update and replace operations. Update operations modify the fields and values of a document while keeping other fields and values unchanged. 您可以使用update和replace操作修改MongoDB集合中的文档。更新操作修改文档的字段和值,同时保持其他字段和值不变。Replace operations substitute all fields and values in an existing document with specified fields and values while keeping the 替换操作将现有文档中的所有字段和值替换为指定的字段和值,同时保持_id field value unchanged._id字段值不变。
The Node.js driver provides the following methods to change documents:Node.js驱动程序提供了以下更改文档的方法:
updateOne()updateMany()replaceOne()
To learn how to replace documents, see the Replace Documents guide.要了解如何替换文档,请参阅《替换文档》指南。
Tip
Interactive Lab互动实验室
This page includes a short interactive lab that demonstrates how to modify data by using the 此页面包括一个简短的交互式实验室,演示如何使用updateMany() method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.updateMany()方法修改数据。您可以直接在浏览器窗口中完成此实验,而无需安装MongoDB或代码编辑器。
To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.要启动实验室,请单击页面顶部的“打开交互式教程”按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮(⛶)。
Update Documents更新文档
To perform an update to one or more documents, create an update document that specifies the update operator (the type of update to perform) and the fields and values that describe the change. Update documents use the following format:要对一个或多个文档执行更新,请创建一个更新文档,指定更新运算符(要执行的更新类型)以及描述更改的字段和值。更新文档使用以下格式:
{
<update operator>: {
<field> : {
...
},
<field> : {
}
},
<update operator>: {
...
}
}
The top level of an update document contains one or more of the following update operators:更新文档的顶层包含以下一个或多个更新运算符:
$set: replaces the value of a field with a specified one:将字段的值替换为指定值$inc: increments or decrements field values:递增或递减字段值$rename: renames fields:重命名字段$unset: removes fields:删除字段$mul: multiplies a field value by a specified number:将字段值乘以指定的数字
See the MongoDB Server manual for a complete list of update operators and their usage.有关更新运算符及其用法的完整列表,请参阅MongoDB Server手册。
The update operators apply only to the fields associated with them in your update document.更新运算符仅适用于更新文档中与其关联的字段。
Note
Aggregation Pipelines in Update Operations更新操作中的聚合管道
If you are using MongoDB Version 4.2 or later, you can use aggregation pipelines made up of a subset of aggregation stages in update operations. For more information on the aggregation stages MongoDB supports in aggregation pipelines used in update operations, see our tutorial on building updates with aggregation pipelines.如果您使用的是MongoDB 4.2或更高版本,则可以在更新操作中使用由聚合阶段子集组成的聚合管道。有关MongoDB在更新操作中使用的聚合管道中支持的聚合阶段的更多信息,请参阅我们关于使用聚合管道构建更新的教程。
Example示例
Consider a document in the 考虑myDBitems集合中的一个文档,其中包含描述待售商品、价格和可用数量的字段:myDB.items collection with fields describing an item for sale, its price, and the quantity available:
{
_id: 465,
item: "Hand-thrown ceramic plate",
price: 32.50,
quantity: 7,
}
If you apply the 如果将$set update operator with a new value for quantity, you can use the following update document:$set更新运算符应用于quantity(数量)的新值,则可以使用以下更新文档:
const myDB = client.db("myDB");
const myColl = myDB.collection("items");
const filter = { _id: 465 };
// update the value of the 'quantity' field to 5
const updateDocument = {
$set: {
quantity: 5,
},
};
const result = await myColl.updateOne(filter, updateDocument);
The updated document resembles the following, with an updated value in the 更新后的文档类似于以下内容,quantity field and all other values unchanged:quantity字段中的值更新,所有其他值不变:
{
_id: 465,
item: "Hand-thrown ceramic plate",
price: 32.50,
quantity: 5,
}
If an update operation fails to match any documents in a collection, it does not make any changes. Update operations can be configured to perform an upsert which attempts to perform an update, but if no documents are matched, inserts a new document with the specified fields and values.如果更新操作无法匹配集合中的任何文档,则不会进行任何更改。更新操作可以配置为执行upsert,该upsert尝试执行更新,但如果没有匹配的文档,则插入具有指定字段和值的新文档。
You cannot modify the 您不能修改文档的_id field of a document nor change a field to a value that violates a unique index constraint. See the MongoDB Server manual for more information on unique indexes._id字段,也不能将字段更改为违反唯一索引约束的值。有关唯一索引的更多信息,请参阅MongoDB服务器手册。
updateOne() Example: Full FileupdateOne()示例:完整文件
Note
Example Setup示例设置
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
This example uses the 此示例使用$set update operator which specifies update values for document fields. For more information on update operators, see the MongoDB update operator reference documentation.$set更新运算符,该运算符指定文档字段的更新值。有关更新运算符的更多信息,请参阅MongoDB更新运算符参考文档。
The following code is a complete, standalone file that performs an update one operation:以下代码是一个完整的独立文件,用于执行更新一操作:
JavaScript
// Update a document更新文档
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string将uri字符串替换为MongoDB部署的连接字符串
const 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设置upsert选项,以便在没有符合筛选条件的文档时插入文档 */
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 errors运行程序并打印任何抛出的错误
run().catch(console.dir);TypeScript
// Update a document更新文档
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string将uri字符串替换为MongoDB部署的连接字符串
const uri = "<connection string uri>";
const client = new MongoClient(uri);
// Define the Movie interface定义电影界面
interface 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选项,以便在没有符合筛选条件的文档时插入文档 */
{ 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 errors运行程序并打印任何抛出的错误
run().catch(console.dir);Running the preceding example results in the following output:运行前面的示例会得到以下输出:
1 document(s) matched the filter, updated 1 document(s)updateMany() Example: Full FileupdateMany()示例:完整文件
Note
Example Setup示例设置
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
The following code is a complete, standalone file that performs an update many operation:以下代码是一个完整的独立文件,用于执行更新操作:
JavaScript
/* Update multiple documents更新多个文档 */
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string将uri字符串替换为MongoDB部署的连接字符串
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
// Get the "movies" collection in the "sample_mflix" database在“sample_mflix”数据库中获取“电影”集合
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create a filter to update all movies with a 'G' rating创建一个筛选器来更新所有评级为“G”的电影
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);TypeScript
/* Update multiple documents更新多个文档 */
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
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 interface创建电影界面
interface Movie {
rated: Rating;
random_review?: string;
}
async function run() {
try {
// Get the "movies" collection in the "sample_mflix" database在“sample_mflix”数据库中获取“电影”集合
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);Running the preceding example, you see an output like the following:运行前面的示例,您会看到如下输出:
Updated 477 documentsAPI DocumentationAPI 文档
To learn more about any of the types or methods discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下API文档: