Replace a Document替换文档¶
If you specify a callback method, 如果指定回调方法,replaceOne()
returns nothing. replaceOne()
将不返回任何内容。If you do not specify one, this method returns a 如果未指定,此方法将返回一个Promise
that resolves to the result object when it completes. Promise
,该Promise
在完成时解析为结果对象。See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.有关更多信息,请参阅我们的承诺和回调指南,或参阅API文档以了解有关结果对象的信息。
You can replace a single document using the collection.replaceOne() method. 可以使用collection.replaceOne()
方法替换单个文档。replaceOne()
accepts a query document and a replacement document. replaceOne()
接受查询文档和替换文档。If the query matches a document in the collection, it replaces the first document that matches the query with the provided replacement document. 如果查询与集合中的文档匹配,它将用提供的替换文档替换与查询匹配的第一个文档。This operation removes all fields and values in the original document and replaces them with the fields and values in the replacement document. 此操作将删除原始文档中的所有字段和值,并将其替换为替换文档中的字段和值。The value of the 除非在替换文档中为_id
field remains the same unless you explicitly specify a new value for _id
in the replacement document._id
显式指定新值,否则_id字段的值保持不变。
You can specify additional options, such as 可以使用可选的upsert
, using the optional options
parameter. options
参数指定其他选项,例如upsert
。If you set the 如果将upsert
option field to true
the method inserts a new document if no document matches the query.upsert
选项字段设置为true
,则如果没有与查询匹配的文档,则该方法将插入新文档。
The 如果在执行过程中发生错误,replaceOne()
method throws an exception if an error occurs during execution. replaceOne()
方法将引发异常。For example, if you specify a value that violates a unique index rule, 例如,如果指定的值违反唯一索引规则,则replaceOne()
throws a duplicate key error
.replaceOne()
将抛出“重复的键错误”。
If your application requires the document after updating, use the collection.findOneAndReplace() method which has a similar interface to 如果应用程序在更新后需要该文档,请使用collection.findOneAndReplace()方法,该方法与replaceOne()
. replaceOne()
具有类似的接口。You can configure 您可以配置findOneAndReplace()
to return either the original matched document or the replacement document.findOneAndReplace()
以返回原始匹配文档或替换文档。
Example示例¶
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB实例,并与包含示例数据的数据库交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例并加载示例数据集的更多信息,请参阅用法示例指南。
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// create a query for a movie to update为要更新的电影创建查询
const query = { title: { $regex: "The Cat from" } };
// create a new document that will be used to replace the existing document创建用于替换现有文档的新文档
const replacement = {
title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
};
const result = await movies.replaceOne(query, replacement);
console.log(`Modified ${result.modifiedCount} document(s)`);
} finally {
await client.close();
}
}
run().catch(console.dir);
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。
const uri = "<connection string uri>";
const client = new MongoClient(uri);
interface Movie {
title: string;
}
async function run() {
try {
await client.connect();
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);
If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:
Modified 1 document(s)