向Cosmos DB添加新属性 [英] Adding a new property to Cosmos DB

查看:124
本文介绍了向Cosmos DB添加新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上很难找到这个问题的答案.

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.

是否可以向所有文档添加新属性? Cosmos DB似乎正在抵抗我尝试过的一切.我必须删除现有文档并制作新文档吗?

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?

如果可能的话,很高兴知道如何使用C#代码执行此操作.不过,Javascript也很好.

It would be nice to know how to do this in C# code, if possible. Javascript is fine too, though.

推荐答案

使用 https://docs.microsoft.com/fr-fr/python/api/azure-cosmos/azure.cosmos.cosmos_client.cosmosclient?view=azure-python#upsertitem-database-or-container-link--document--options-none- 非常简单.

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))

这篇关于向Cosmos DB添加新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆