Reputation: 3030
I've actually had quite a bit of trouble finding an answer to this question.
If I create a new document in a collection, I can give it whatever properties I want.
Is there a way to add a new property to all my documents? Cosmos DB seems to be resisting everything I've tried. Do I have to delete the existing documents and make new ones?
It would be nice to know how to do this in C# code, if possible. Javascript is fine too, though.
Upvotes: 1
Views: 8493
Reputation: 1
Using https://learn.microsoft.com/fr-fr/python/api/azure-cosmos/azure.cosmos.cosmos_client.cosmosclient?view=azure-python#upsertitem-database-or-container-link--document--options-none- was pretty straightforward.
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.errors as errors
import azure.cosmos.http_constants as http_constants
import os
import json
url = 'https://yourdb.documents.azure.com:443/'
key = 'key'
client = cosmos_client.CosmosClient(url, {'masterKey': key})
database_id = 'database_id '
container_id = 'container_id '
for item in client.QueryItems("dbs/" + database_id + "/colls/" + container_id,
'SELECT * FROM ' + container_id + ' ',
{'enableCrossPartitionQuery': True}):
item["field"] = "value"
newItem = client.UpsertItem("dbs/" + database_id + "/colls/" + container_id, item)
print(json.dumps(newItem, indent=True))
Upvotes: 0
Reputation: 7200
CosmosDB does not support partial document updates so you would have to Update all of your existing documents with the new property if you really need it there. There are many ways you can do that including stored procedures.
If you are ok to use C# then you can do that easily with Cosmonaut
var items = await cosmoStore.Query().ToListAsync();
foreach(var item in items){
item.YourProperty = "YourValue";
}
await cosmosStore.UpdateRangeAsync(items);
When selecting the items your value will default to the default property value if it's not present and by updating it, it will be added.
Upvotes: 1