Navigation

Insert or Update in a Single Operation

If your application stores and modifies data in MongoDB, you probably use insert and update operations. 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:

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.

Suppose your application tracks the current location of food trucks, storing the nearest address data in a MongoDB collection that resembles the following:

[
{ 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. 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:

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:

[
{ name: "Haute Skillet", address: "42 Avenue B" },
{ name: "Lady of the Latke", address: "35 Fulton Rd" },
{ name: "Deli Llama", address: "3 Nassau St" },
...
]
Give Feedback