Replace a Document替换一个文档
You can replace a single document using the collection.replaceOne()您可以使用 method.
collection.replaceOne()
方法替换单个文档。
replaceOne()
accepts a query document and a replacement document. 接受查询文档和替换文档。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()
将抛出duplicate key error
。
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实例
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.将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 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);
If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:
Modified 1 document(s)