文档菜单
文档首页
/ / /
Node.js 驱动程序
/ /

替换文档

您可以使用以下方法替换单个文档:collection.replaceOne() 方法。replaceOne() 接受一个查询文档和一个替换文档。如果查询匹配集合中的文档,则使用提供的替换文档替换与查询匹配的第一个文档。此操作会删除原始文档中所有字段和值,并用替换文档中的字段和值替换它们。除非在替换文档中显式指定新值,否则 _id 字段的值保持不变。

您可以使用可选的 options 参数指定更多选项,例如 upsert。如果将 upsert 选项字段设置为 true,则在没有文档匹配查询的情况下,该方法插入一个新文档。

如果在执行过程中发生错误,replaceOne() 方法会抛出异常。例如,如果您指定违反唯一索引规则的值,replaceOne() 会抛出 duplicate key error

注意

如果您的应用程序需要更新后的文档,请使用具有与 replaceOne() 相似界面的 collection.findOneAndReplace() 方法。您可以将 findOneAndReplace() 配置为返回原始匹配文档或替换文档。

注意

您可以使用此示例连接到MongoDB实例并交互操作包含样本数据的数据库。要了解更多关于连接到您的MongoDB实例和加载样本数据集的信息,请参阅使用示例指南.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a query for documents where the title contains "The Cat from"
16 const query = { title: { $regex: "The Cat from" } };
17
18 // Create the document that will replace the existing document
19 const replacement = {
20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
21 };
22
23 // Execute the replace operation
24 const result = await movies.replaceOne(query, replacement);
25
26 // Print the result
27 console.log(`Modified ${result.modifiedCount} document(s)`);
28 } finally {
29 await client.close();
30 }
31}
32run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10}
11
12async function run() {
13 try {
14 const database = client.db("sample_mflix");
15 const movies = database.collection<Movie>("movies");
16
17 const result = await movies.replaceOne(
18 { title: { $regex: "The Cat from" } },
19 {
20 title: `The Cat from Sector ${Math.floor(Math.random() * 1000) + 1}`,
21 }
22 );
23 console.log(`Modified ${result.modifiedCount} document(s)`);
24 } finally {
25 await client.close();
26 }
27}
28run().catch(console.dir);

运行上述示例,您将看到以下输出

Modified 1 document(s)

返回

更新多个文档