Docs HomeNode.js

Update a Document更新一个文档

You can update a single document using the collection.updateOne() method. 您可以使用collection.updateOne()方法更新单个文档。The updateOne() method accepts a filter document and an update document. updateOne()方法接受一个筛选文档和一个更新文档。If the query matches documents in the collection, the method applies the updates from the update document to fields and values of them. 如果查询与集合中的文档匹配,则该方法将更新文档中的更新应用于字段和值。The update document contains update operators that instruct the method on the changes to make to the matches.更新文档包含更新运算符,这些运算符指示方法对匹配项进行更改。

You can specify additional query options using the options object passed as the second parameter of the updateOne() method. 您可以使用作为updateOne()方法的第二个参数传递的options对象来指定其他查询选项。Set the upsert option to true to create a new document if no documents match the filter. 如果没有与筛选器匹配的文档,则将upsert选项设置为true以创建新文档。For additional information, see the updateOne() API documentation.有关更多信息,请参阅updateOne()API文档

updateOne() throws an exception if an error occurs during execution. 如果在执行过程中发生错误,则引发异常。If you specify a value in your update document for the immutable field _id, the method throws an exception. 如果在更新文档中为不可变字段_id指定了一个值,则该方法将抛出异常。If your update document contains a value that violates unique index rules, the method throws a duplicate key error exception.如果更新文档中包含的值违反了唯一索引规则,则该方法将引发duplicate key error异常。

Note

If your application requires the document after updating, consider using the collection.findOneAndUpdate() method, which has a similar interface to updateOne() but also returns the original or updated document.如果您的应用程序在更新后需要文档,请考虑使用collection.findOneAndUpdate()方法,该方法与updateOne()有类似的接口,但也返回原始或更新的文档。

Example实例

The following example uses the $set update operator which specifies update values for document fields. 以下示例使用$set更新运算符,该运算符指定文档字段的更新值。For more information on update operators, see the MongoDB update operator reference documentation.有关更新运算符的更多信息,请参阅MongoDB更新运算符参考文档

Note

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 filter for a movie to update为要更新的电影创建筛选器
const filter = { title: "Random Harvest" };

// this option instructs the method to create a document if no documents match the filter该选项指示该方法在没有与筛选器匹配的文档的情况下创建文档
const options = { upsert: true };

// create a document that sets the plot of the movie创建一个设置电影情节的文档
const updateDoc = {
$set: {
plot: `A harvest of random numbers, such as: ${Math.random()}`
},
};

const result = await movies.updateOne(filter, updateDoc, options);
console.log(
`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
);
} finally {
await client.close();
}
}
run().catch(console.dir);

If you run the example above, you should see the following output:如果运行上面的示例,您应该会看到以下输出:

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