Skip to main content

Is there an "upsert" option in the MongoDB insert command?

Updated 1 min readMarkdown
Part of seriesMongoDB
Is there an "upsert" option in the MongoDB
insert command?

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:

  • 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.

Sources:

Insert or Update in a Single Operation — Node.js. www.mongodb.com/docs/drivers/node/current/fundamentals/crud/write-operations/upsert.

About the author

  • Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, MySQL, MongoDB. Love collaborating & making a difference

No comments yet. Be the first to comment.

More from this blog