Overview概述
If your application stores and modifies data in MongoDB, you probably use insert and update operations. In certain workflows, whether you perform an insert or update operation depends on whether the document exists. In these cases, you can streamline your application logic by using the 如果你的应用程序在MongoDB中存储和修改数据,你可能会使用插入和更新操作。在某些工作流中,是执行插入操作还是更新操作取决于文档是否存在。在这些情况下,您可以通过使用以下方法中的upstart选项来简化应用程序逻辑:upsert option available in the following methods:
If the query filter passed to these methods does not find any matches and you set the 如果传递给这些方法的查询筛选器没有找到任何匹配项,并且您将upsert option to true, MongoDB inserts the update document. Let's go through an example.upsert选项设置为true,MongoDB将插入更新文档。让我们来看一个例子。
Performing an Update执行更新
Suppose your application tracks the current location of food trucks, storing the nearest address data in the 假设您的应用程序跟踪食品卡车的当前位置,将最近的地址数据存储在myDB.foodTrucks collection, which resembles the following:myDB.foodTrucks集合中,类似于以下内容:
[
{ name: "Haute Skillet", address: "42 Avenue B" },
{ name: "Lady of the Latke", address: "35 Fulton Rd" },
...
]
As an application user, you read about a food truck changing its regular location and want to apply the update. This update might resemble the following:作为一名应用程序用户,您读到一辆食品车改变了其常规位置,并希望应用更新。此更新可能类似于以下内容:
const myDB = client.db("myDB");
const myColl = myDB.collection("foodTrucks");
const query = { name: "Deli Llama" };
const update = { $set: { name: "Deli Llama", address: "3 Nassau St" }};
const options = {};
const result = await myColl.updateOne(query, update, options);
If a food truck named "Deli Llama" exists, the method call above updates the document in the collection. However, if there are no food trucks named "Deli Llama" in your collection, no changes are made.如果存在名为“Deli Llama”的食品车,则上述方法调用会更新集合中的文档。但是,如果您的集合中没有名为“Deli Llama”的食品车,则不会进行任何更改。
Performing an Upsert执行upsert
Consider the case in which you want to add information about the food truck even if it does not yet exist in your collection. Rather than first querying whether it exists to determine whether to insert or update the document, we can set 考虑这样一种情况,即即使您的集合中还不存在食品车,您也希望添加有关食品车的信息。我们可以在调用upsert to true in our call to updateOne() as follows:updateOne()时将upstart设置为true,而不是首先查询它是否存在以确定是插入还是更新文档,如下所示:
const query = { name: "Deli Llama" };
const update = { $set: { name: "Deli Llama", address: "3 Nassau St" }};
const options = { upsert: true };
const result = await myColl.updateOne(query, update, options);
After you run the operation above, your collection looks similar to the following, even if the 运行上述操作后,即使在操作之前"Deli Llama" document did not exist in your collection before the operation:"Deli Llama"文档不存在于您的集合中,您的集合看起来也类似于以下内容:
[
{ name: "Haute Skillet", address: "42 Avenue B" },
{ name: "Lady of the Latke", address: "35 Fulton Rd" },
{ name: "Deli Llama", address: "3 Nassau St" },
...
]