Docs HomeNode.js

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

Overview概述

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.让我们来举个例子。

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 = {};
myColl.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.但是,如果您的集合中没有名为“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 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 };
myColl.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" },
...
]