Insert or Update in a Single Operation在单个操作中插入或更新

If your application stores and modifies data in MongoDB, you probably use insert and update operations. 如果应用程序在MongoDB中存储和修改数据,则可能会使用插入和更新操作。In certain workflows, you may need to choose between an insert and update depending on whether the document exists. 在某些工作流中,可能需要根据文档是否存在在插入和更新之间进行选择。In these cases, you can streamline your application logic by using the upsert option available in the following methods:在这些情况下,您可以使用以下方法中提供的upsert选项来简化应用程序逻辑:

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. 如果传递给这些方法的查询筛选器未找到任何匹配项,并且您将upsert选项设置为true,则MongoDB将插入更新文档。Let's go through an example.让我们看一个例子。

Suppose your application tracks the current location of food trucks, storing the nearest address data in a MongoDB collection that resembles the following:假设您的应用程序跟踪食品卡车的当前位置,将最近的地址数据存储在MongoDB集合中,类似于以下内容:

[
  { 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 query = { name: "Deli Llama" };
const update = { $set: { name: "Deli Llama", address: "3 Nassau St" }};
const options = {};
collection.updateOne(query, update, options);

If a food truck named "Deli Llama" exists, the method call above updates the document in the collection. 如果名为“Deli Llama”的食品卡车存在,则上面的方法调用将更新集合中的文档。However, if there are no food trucks named "Deli Llama" in your collection, no changes are made.但是,如果您的集合中没有名为“德利骆驼”的食品卡车,则不会进行任何更改。

Consider the case in which you want to add information about the food truck even if it does not currently exist in your collection. 考虑你想添加关于食品卡车的信息,即使它目前不存在于你的集合中。Rather than first querying whether it exists to determine whether we need to insert or update the document, we can set upsert to true in our call to updateOne() as follows:我们可以在对updateOne()的调用中将upsert设置为true,而不是首先查询它是否存在以确定是否需要插入或更新文档,如下所示:

const query = { name: "Deli Llama" };
const update = { $set: { name: "Deli Llama", address: "3 Nassau St" }};
const options = { upsert: true };
collection.updateOne(query, update, options);

After you run the operation above, your collection should resemble the following, whether the "Deli Llama" document existed in your collection beforehand:运行上述操作后,无论您的集合中是否存在“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" },
  ...
]