Overview概述
In this guide, you can learn how to use Node.js driver to perform a replace operation on a document in a MongoDB collection. A replace operation performs differently than an update operation. An update operation modifies only the specified fields in a target document. 在本指南中,您可以学习如何使用Node.js驱动程序对MongoDB集合中的文档执行替换操作。替换操作与更新操作的执行方式不同。更新操作仅修改目标文档中的指定字段。A replace operation removes all fields in the target document and replaces them with new ones.替换操作会删除目标文档中的所有字段,并用新字段替换它们。
Replace a Document替换文档
To perform a replacement operation, create a replacement document that consists of the fields and values that you want to use in your replace operation. Replacement documents use the following format:要执行替换操作,请创建一个替换文档,其中包含要在替换操作中使用的字段和值。替换文件使用以下格式:
{
<field>: {
<value>
},
<field>: {
...
}
}
Replacement documents are the documents that you want to take the place of existing documents that match the query filters.替换文档是您希望替换与查询筛选器匹配的现有文档的文档。
You can specify more options, such as 您可以使用可选选项参数指定更多选项,例如upsert, using the optional options parameter. If you set the upsert option field to true the method inserts a new document if no document matches the query.upsert。如果将upstart选项字段设置为true,则如果没有文档与查询匹配,该方法将插入一个新文档。
The 如果执行过程中发生错误,replaceOne() method throws an exception if an error occurs during execution. For example, if you specify a value that violates a unique index rule, replaceOne() throws a duplicate key error.replaceOne()方法会抛出异常。例如,如果指定的值违反了唯一索引规则,replaceOne()将抛出duplicate key error(重复键错误)。
Note
If your application requires the document after updating, use the collection.findOneAndReplace() method which has a similar interface to 如果您的应用程序在更新后需要该文档,请使用replaceOne(). collection.findOneAndReplace()方法,该方法具有与replaceOne()类似的接口。You can configure 您可以配置findOneAndReplace() to return either the original matched document or the replacement document.findOneAndReplace()以返回原始匹配文档或替换文档。
Example示例
Consider a document in the 考虑myDB.items collection with fields describing an item for sale, its price, and the quantity available:myDB.items集合中的一个文档,其中包含描述待售商品、价格和可用数量的字段:
{
_id: 501,
item: "3-wick beeswax candle",
price: 18.99,
quantity: 10,
}
Suppose you wanted to replace this document with one that contains a description for an entirely different item. Your replacement operation might resemble the following:假设您想用包含完全不同项目描述的文档替换此文档。您的更换操作可能类似于以下操作:
const myDB = client.db("myDB");
const myColl = myDB.collection("items");
const filter = { _id: 501 };
// replace the matched document with the replacement document用替换文档替换匹配的文档
const replacementDocument = {
item: "Vintage silver flatware set",
price: 79.15,
quantity: 1,
};
const result = await myColl.replaceOne(filter, replacementDocument);
The replaced document contains the contents of the replacement document and the immutable 被替换的文档包含替换文档的内容和不可变_id field as follows:_id字段,如下所示:
{
_id: 501,
item: "Vintage silver flatware set",
price: 79.15,
quantity: 1,
}
If a replace operation fails to match any documents in a collection, it does not make any changes. Replace operations can be configured to perform an upsert which attempts to perform the replacement, but if no documents are matched, it 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服务器手册。
replaceOne() Example: Full FilereplaceOne()示例:完整文件
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 a replace one operation:以下代码是一个完整的独立文件,用于执行替换操作:
JavaScript
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 database and collection on which to run the operation获取要在其上运行操作的数据库和集合
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create a query for documents where the title contains "The Cat from"为标题包含“the Cat from”的文档创建查询
const query = { title: { $regex: "The Cat from" } };
// Create the document that will replace the existing document创建将替换现有文档的文档
const replacement = {
title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
};
// Execute the replace operation执行替换操作
const result = await movies.replaceOne(query, replacement);
// Print the result打印结果
console.log(`Modified ${result.modifiedCount} document(s)`);
} finally {
await client.close();
}
}
run().catch(console.dir);TypeScript
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);
interface Movie {
title: string;
}
async function run() {
try {
const database = client.db("sample_mflix");
const movies = database.collection<Movie>("movies");
const result = await movies.replaceOne(
{ title: { $regex: "The Cat from" } },
{
title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
}
);
console.log(`Modified ${result.modifiedCount} document(s)`);
} finally {
await client.close();
}
}
run().catch(console.dir);Running the preceding example results in the following output:运行前面的示例会得到以下输出:
Modified 1 document(s)API Documentation文档
To learn more about any of the types or methods discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下API文档: