Docs Menu
Docs Home
/ / /
Node.js Driver
/ / /

Insert or Update in a Single Operation

On this page

  • Overview
  • Performing an Update
  • Performing an Upsert

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 upsert option available in the following methods:

  • updateOne()

  • replaceOne()

  • updateMany()

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 the myDB.foodTrucks collection, which 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 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. 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 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:

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 looks similar to the following, even if the "Deli Llama" document did not exist in your collection before the operation:

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

Back

Update Arrays in a Document