Given a collection of documents, and a list of documents that need to be updated in the collection, I’m struggling to understand whether in a single query I can execute a single operation to upsert each of the items in the list.
For example, if I have a list of 10 items, I’d like to:
Check to see if an item exists with the same id
If an item does exist, update the fields in the database with the fields provided in my list object
If not, create a new document in the collection identical to what I passed
I tried looking at updateMany but it looks like it is built to update each item the same way rather than process a list of single items against the same rule.
I considered generating an aggregation pipeline via $map to do this, but I thought that maybe I was overcomplicating the issue. What is the idiomatic way to handle this scenario? Thanks!
You can use the bulkWrite method to achieve this behavior. The bulkWrite method allows you to perform a number of different write operations in a single command, including update and insert operations.
Here’s an example of how you could use bulkWrite to upsert a list of documents:
This will update the documents with the matching _id field in the filter clause, or insert a new document if no matching documents were found. The upsert option is set to true to specify that an upsert should be performed.
You can also use the bulkWrite method to perform other types of write operations, such as delete operations.