Check if MongoDB upsert did an insert or an update
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
When working with MongoDB, an "upsert" operation is a powerful feature allowing developers to specify an update to a document while also having the option to insert the document if it doesn't exist. This blend of update and insert reduces the need for separate operations to check, update, and create records, thus streamlining database interactions and reducing latency.
This article will delve into how to determine if an upsert operation in MongoDB resulted in an insertion or an update, exploring technical elements and providing examples throughout.
Understanding Upsert in MongoDB
In MongoDB, upsert is an option used with the update() operation. By setting the upsert flag to true, the database is instructed to perform either of the following depending on the presence of the document:
- Update: If the document exists, it will be updated with the specified changes.
- Insert: If the document does not exist, MongoDB will create it.
Here is how the update operation with upsert typically looks:
Parameters
<query>: The condition to match the document.<update>: The modifications to apply if the document is found.upsert: true: The configuration indicating the database should create the document if it does not exist.
Upsert Result Analysis
MongoDB provides a way to identify whether an upsert operation performed an insert or an update through the result's WriteResult object.
WriteResult Object
Upon performing an upsert, MongoDB returns a WriteResult (in older versions) or UpdateResult object (in modern versions with drivers like Node.js) which contains fields relevant to the operation:
matchedCount: Count of documents matched by the query.modifiedCount: Count of documents that were modified.upsertedId: The unique identifier of the inserted document. This field only appears if an insert operation occurred.
Example Case
Let's demonstrate this with a practical example in a Node.js environment using the MongoDB driver.
Analysis
- Insert Occurred: When the operation results in a new document,
result.upsertedIdwill be populated with an identifier. - Update Occurred: If the document was only modified and existed previously,
result.upsertedIdwill beundefinedor absent. Instead, you'll find a positivematchedCount.
A Closer Look at upsertedId
The upsertedId provides the ObjectId of the document that was inserted as a result of an upsert operation. It serves as a key indicator differentiating between an insert and an update.
Summary Table
To summarize the operation outcomes:
| Outcome | matchedCount | upsertedId | Explanation |
| Insert | 0 | ObjectId (present) | No documents matched, new document created. |
| Update | ≥ 1 | undefined | Document(s) matched, updated in place. |
Enhancements to Consider
- Optimistic Locking: While
upsertis powerful, consider using versioning or timestamps to manage concurrent document updates. - Error Handling: Always handle potential errors from MongoDB operations to ensure smooth application behavior.
Conclusion
MongoDB's upsert operation is a versatile tool, capable of seamlessly managing records by determining whether an insert or update is appropriate. By leveraging the returned WriteResult or UpdateResult from these operations, developers can precisely track and act upon the nature of the database changes, enhancing application's logic and data consistency.
With this understanding, developers can integrate MongoDB upserts efficiently into their projects, optimizing both performance and code simplicity, especially in complex applications with dynamic data management needs.

