Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Cosmos DB - Update existing documents with an additional field

Existing Cosmos DB documents need to be altered/updated with a new property & also existing documents of other collections need to be updated with the same new property along with its value.

Is there any recommended way or tool available to update existing documents on Cosmos DB, or is writing the custom c# application/PowerShell script using Cosmos DB SDK is the only option?

Example:

Existing user document

{
   id:[email protected],
   name: "abc",
   country: "xyz"
}  

Updated user document

{
   id:[email protected],
   name: "abc",
   country: "xyz",
   guid:"4334fdfsfewr"  //new field
} 

Existing order document of the user

{
   id:[email protected],
   user: "[email protected]",
   date: "09/28/2020",
   amt: "$45"
}  

Updated order document of the user

{
   id:[email protected],
   user: "[email protected]",
   userid: "4334fdfsfewr",  // new field but with same value as in user model
   date: "09/28/2020",
   amt: "$45"
}  
like image 958
191180rk Avatar asked Sep 28 '20 13:09

191180rk


People also ask

What is Upsert in cosmos?

Upsert is an outbound action to either update or create a new record in Microsoft Azure Cosmos DB collection. This operation can be performed either in bulk or a single record by specifying Object/Record ID(s) and Partition Key.

Can we update partition key in Cosmos DB?

You can only set it when you create a new container. If you do need to change a partition key, you need to create a new container and migrate your data to that one.

How do I add a column to Cosmos DB?

If you are trying to update the ID "108-406-004" to add a new property, you can use a copy activity with the option "Write behaviour" as "Upsert". Using this option will automatically add the new property to the record in Cosmos DB.


1 Answers

I'd probably go with:

  1. Update user documents through a script
  2. Have Azure Function with Cosmosdb trigger that would listen to changes on users documents and update orders appropriately

[UPDATE] whatever type of script you feel best with: PS, C#, Azure Functions... now, what do you mean they need to be altered with the new property "on the same time"? i'm not sure that's possible in any way. if you want such an effect then i guess your best bet is:

  1. create new collection/container for users
  2. have an Azure Function that listens to a change feed for your existing users container (so, with StartFromBeginning option)
  3. update your documents to have new field and store them in a newly created container
  4. once done, switch your application to use new container

its your choice how would you change other collections (orders): using changeFeed & Azure Functions from old or new users container.

PS. Yes, whatever flow i'd go with, it would still be Azure Functions with Cosmos DB trigger.

like image 105
dee zg Avatar answered Sep 28 '22 02:09

dee zg