Upserting List of Documents

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:

  1. Check to see if an item exists with the same id
  2. If an item does exist, update the fields in the database with the fields provided in my list object
  3. 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!

Hi @Brian_Sump ,

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:

const documentsToUpsert = [
  {
    updateOne: {
      filter: { _id: 1 },
      update: { $set: { field1: "value1" } },
      upsert: true
    }
  },
  {
    updateOne: {
      filter: { _id: 2 },
      update: { $set: { field2: "value2" } },
      upsert: true
    }
  },
  {
    updateOne: {
      filter: { _id: 3 },
      update: { $set: { field3: "value3" } },
      upsert: true
    }
  }
];

await collection.bulkWrite(documentsToUpsert);

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.

Will that work?

Thanks

1 Like

This should work - thanks!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.