How to update if exists otherwise insert new document?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
In the world of databases and data management, a common operation is the need to ensure that a document exists in the database. If it does, the document should be updated; if not, a new document should be inserted. This operation is typically referred to as "upsert" (a portmanteau of "update" and "insert"). This article explores the concept of the upsert operation, provides technical explanations, explores scenarios in different database systems, and supplies examples to illustrate the process.
Concept of Upsert
An upsert operation is a transactional command sent to a database that attempts to update an existing document with new values. If the document is not found, the command inserts the new document into the collection or table. It streamlines tasks in situations where the presence of a document is uncertain, mitigating the need for separate queries for checking existence, inserting, or updating.
Implementations in Different Databases
MongoDB
MongoDB is a NoSQL database known for its flexible document model. It natively supports upsert operations using the $updateOne, $updateMany, or $replaceOne methods, which include an upsert option.
Example
In this example, the update will target a document with an _id of 1. If such a document does not exist, a new one will be inserted with the provided criteria and updates.
SQL Databases
For SQL databases like MySQL and PostgreSQL, the upsert functionality is available but implemented differently.
MySQL
MySQL provides the ON DUPLICATE KEY UPDATE clause for upsert operations.
In this example, the insertion will occur based on the primary key. If a collision happens (like with a matching id), an update action is executed instead.
PostgreSQL
PostgreSQL uses the INSERT ... ON CONFLICT clause, which functions similarly.
It addresses conflicts related to specified columns (in this case, id) by executing an update on them.
Performance Considerations
Upserts may seem complicated compared to traditional insert and update statements but offer significant performance benefits due to reduced transaction overhead, particularly in high-concurrency systems. They decrease the number of queries necessary for maintaining data concurrency, optimizing database workloads and resource usage.
Handling Concurrency
An effective upsert strategy should also consider data concurrency scenarios. Concurrency can lead to race conditions where simultaneous transactions modify the same data. Utilizing database locking mechanisms, isolation levels, and retry logic can assist in handling these issues.
Use Cases
Upsert operations are particularly useful in scenarios such as:
- Data Synchronization: Keeping local datasets and central databases synchronized.
- Web Applications: When ensuring user or session details are consistently updated without redundant checks.
- ETL Processes: Updating or inserting data from varying sources efficiently during extraction, transformation, and loading phases.
Summary Table
| Database | Upsert Method | Example Command |
| MongoDB | updateMany with upsert | db.collection.updateOne({ criteria }, { update }, { upsert: true }) |
| MySQL | ON DUPLICATE KEY UPDATE | INSERT INTO table ... ON DUPLICATE KEY UPDATE ... |
| PostgreSQL | ON CONFLICT | INSERT INTO table ... ON CONFLICT ... DO UPDATE ... |
Conclusion
Upsert operations provide database users and developers a robust mechanism to handle uncertainty in document existence. They reduce complexity by combining what would traditionally be two separate tasks into one efficient operation. When implementing upserts, understanding the behavior aligning with your specific database system's capability is crucial to ensure optimal application performance and reliability.
Related reading
- How to update master table while updating materialized view
- How to update multiple items in a DynamoDB table at once
- How to update SQLAlchemy row entry?
- How to update the _id of one MongoDB Document?
- How to update values using pymongo?
- How to upgrade AWS RDS Aurora MySQL 5.6 to 5.7
- How to upload and retrieve file in mongodb in spring boot application without using GridFSTemplate?
- How to use 2 or more databases with spring?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.