Home » upsert true in MongoDB

upsert true in MongoDB

  • by
upsert true in MongoDB

1. Overview

In this article, we will understand when to use upsert true in your MongoDB queries.

2. MongoDB upsert

You probably could have used update and insert operations to change or store your application data in MongoDB.

For example, the following inserts a new document into your MongoDB collection.

db.collection.insertOne(<document>)
// you can also use insertMany, or bulk write for inserting multiple documents

Similaryly, you can update an existing document using updateOne or updateMany operations.

db.collection.updateOne(<query>, <values to change>)

In certain workflows, you may need to choose between an insert and an 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:

  • updateOne
  • replaceOne
  • updateMany

By default, the upsert option is set to false.

If the query filter passed to these methods does not find any matches in the collection and you set the upsert option to true, MongoDB inserts the document.

An upsert is a hybrid of update and insert, you should only use it when it is really required. It is best fit for conditional updates.

  1. If there is a match, updates the matched document.
  2. If there is no match, inserts a new document.

However, to update an existing document or inserting a brand new document, do not use upsert.

3. upsert true in MongoDB

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

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

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" },  ...]

4. Conclusion

To sum up, we have learned the purpose and when to use upsert true in MongoDB queries. To learn more about other MongoDB concepts, refer to these articles.

Leave a Reply

Your email address will not be published. Required fields are marked *