10
votes

Can I write an UPDATE statement for Azure Cosmos DB? The SQL API supports queries, but what about updates?

In particular, I am looking to update documents without having to retrieve the whole document. I have the ID for the document and I know the exact path I want to update within the document. For example, say that my document is

{
  "id": "9e576f8b-146f-4e7f-a68f-14ef816e0e50",
  "name": "Fido",
  "weight": 35,
  "breed": "pomeranian",
  "diet": {
    "scoops": 3,
    "timesPerDay": 2
  }
}

and I want to update diet.timesPerDay to 1 where the ID is "9e576f8b-146f-4e7f-a68f-14ef816e0e50". Can I do that using the Azure SQL API without completely replacing the document?

4
FYI related to your question (though not exactly the same) - an answer going into more detail regarding select vs update / insert / delete along with sdk calls to deal with those (though the updates done via SDK are still done as full document replacement, as Nick pointed out in his answer) - stackoverflow.com/a/46873986/272109David Makogon

4 Answers

12
votes

The Cosmos DB SQL language only supports the Select statement.

Partially updating a document isn't supported via the sql language or the SQL API.

People have made it clear that that's a feature they want so there is a highly upvoted request for it that can be found here: https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/6693091-be-able-to-do-partial-updates-on-document

Microsoft has already started to work on that so the only thing you can do is wait.

3
votes

To elaborate more on this, Updating partially a document in CosmosDb on the server isn’t possible, instead you can do whatever you need to do in the memory.In order to literally UPDATE the document, you will have to to retrieve the entire document from the CosmosDb, update the property/properties that you need to update and then call the ‘Replace’ method in the CosmosDb SDK to replace the document in question. Alternatively you can also use ‘Upsert’ which checks if the document already exists and performs an ‘Insert’ if true or ‘Replace’ if false.

NOTE : Make sure you have the latest version of the document before you commit an update!

As Nick mentioned Cosmosdb team is working on the partial update.

0
votes

As of 25.05.2021 this feature is available in private preview and will hopefully be in GA soon.

https://azure.microsoft.com/en-us/updates/partial-document-update-for-azure-cosmos-db-in-private-preview/

-3
votes

Use Robo3T to update/delete multiple records with mongo db commands. Make sure your query includes the partition key.

db.getCollection('ListOfValues').updateMany({type:'PROPOSAL', key:"CITI"},{$set: {"key":"CITIBANK"}})

db.getCollection('ListOfValues').deleteMany({type:'PROPOSAL', key:"CITI"})