Update a Document更新文档¶
If you specify a callback method, 如果指定回调方法,updateOne()
returns nothing. updateOne()
将不返回任何内容。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 see the API documentation for information on the result object.有关更多信息,请参阅我们的承诺和回调指南,或参阅API文档以了解有关结果对象的信息。
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. updateOne()
将引发异常。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.
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.Copy.FordNo.UpDebug()
方法,它具有类似于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更新运算符参考文档。
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 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);
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 {
plot: string;
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.updateOne(
{ title: "Random Harvest" },
{
$set: {
plot: `A harvest of random numbers, such as: ${Math.random()}`,
},
},
{ upsert: true }
);
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)