DocumentDB: What's the point of "Upsert"?

Simon Ordo picture Simon Ordo · Jul 26, 2017 · Viewed 9.5k times · Source

I'm trying to understand this part of the API so I can update documents in the most efficient way possible.

Given the following:

  • "Replace" requires that a document already exists
  • "Upsert" doesn't require that a document exists, but needs the document ID if it's going to do an update.
  • Neither command can do partial document updates, which means I can't think of any scenario where I wouldn't have to query the document first, then make the change to the affected property, then replace/upsert the entire document.

If I always have to query the document first anyway so as to avoid wiping out any property values that aren't passed back to the upsert/replace, and I can't do a partial updates, what's the point of having both upsert and replace?

Am I missing the intended use cases for these two commands?

Answer

Jesse Carter picture Jesse Carter · Jul 26, 2017

You've already described the key differences between the two. Upsert will create a document if it doesn't already exist otherwise overwrite it. Replace requires that a document already exist and then overwrites it. Which to use is a concern of your application. There are certain circumstances where you would want to use replace because if the document didn't already exist it would constitute an error in your business logic. Otherwise they are very similar.

I understand that the lack of being able to do a partial update can appear frustrating. However, Cosmos has a powerful server side programming model in the form of Stored Procedures which you write in Javascript. You could easily create a SPROC that receives a partial document and updates or adds only those properties that are new or changed which would give you the functionality you're ultimately looking for.