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

更新文档

您可以使用collection.updateOne()方法更新单个文档。该updateOne()方法接受一个过滤器文档和一个更新文档。如果查询与集合中的文档匹配,则该方法将更新文档应用更新文档中的字段和值。更新文档包含更新运算符,指示方法对匹配项进行更改。

您可以使用作为updateOne()方法第二个参数传递的options对象来指定更多查询选项。将upsert选项设置为true,如果没有文档与过滤器匹配,则创建一个新的文档。有关更多信息,请参阅updateOne() API 文档。

updateOne()方法如果在执行过程中发生错误,则会抛出异常。如果您在更新文档中为不可变字段_id指定了一个值,该方法将抛出异常。如果您的更新文档包含违反唯一索引规则的值,该方法将抛出重复键错误异常。

注意

如果您的应用程序需要在更新后获取文档,请考虑使用具有与updateOne()类似界面的collection.findOneAndUpdate()方法,该方法返回原始或更新后的文档。

以下示例使用$set更新运算符,该运算符指定文档字段的更新值。有关更新运算符的更多信息,请参阅MongoDB更新运算符参考文档。

注意

您可以使用此示例连接到MongoDB实例并与之交互,该实例包含示例数据。有关连接到您的MongoDB实例和加载示例数据集的更多信息,请参阅用法示例指南.

1// Update a document
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async function run() {
11 try {
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a filter for movies with the title "Random Harvest"
16 const filter = { title: "Random Harvest" };
17
18 /* Set the upsert option to insert a document if no documents match
19 the filter */
20 const options = { upsert: true };
21
22 // Specify the update to set a value for the plot field
23 const updateDoc = {
24 $set: {
25 plot: `A harvest of random numbers, such as: ${Math.random()}`
26 },
27 };
28
29 // Update the first document that matches the filter
30 const result = await movies.updateOne(filter, updateDoc, options);
31
32 // Print the number of matching and modified documents
33 console.log(
34 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
35 );
36 } finally {
37 // Close the connection after the operation completes
38 await client.close();
39 }
40}
41// Run the program and print any thrown errors
42run().catch(console.dir);
1// Update a document
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10// Define the Movie interface
11interface Movie {
12 plot: string;
13 title: string;
14}
15
16async function run() {
17 try {
18 const database = client.db("sample_mflix");
19 const movies = database.collection<Movie>("movies");
20
21 /* Update a document that has the title "Random Harvest" to have a
22 plot field with the specified value */
23 const result = await movies.updateOne(
24 { title: "Random Harvest" },
25 {
26 $set: {
27 plot: `A harvest of random numbers, such as: ${Math.random()}`,
28 },
29 },
30 /* Set the upsert option to insert a document if no documents
31 match the filter */
32 { upsert: true }
33 );
34
35 // Print the number of matching and modified documents
36 console.log(
37 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`
38 );
39 } finally {
40 // Close the connection after the operation completes
41 await client.close();
42 }
43}
44// Run the program and print any thrown errors
45run().catch(console.dir);

如果您运行上面的示例,您将看到以下输出

1 document(s) matched the filter, updated 1 document(s)

返回

更新 & 替换