【问题标题】:How to update cosmos db document using c#如何使用 c# 更新 cosmos db 文档
【发布时间】:2019-11-13 05:27:24
【问题描述】:

如果文件名已经存在,我想更新 cosmos DB 中的文档。为此,我传递了一个会带来结果的查询,我想更新该结果。我想将修改日期设置为它。如果它是新创建的,如果它已经存在,则添加修改日期。
我正面临更新它的问题,这将在其他部分出现。
这是我的代码 sn-p:

        Class1 obj = new Class1()
        {
            BlobPath = "/container",
            size = (int)myBlob.Length,
            Name = name,
            CreationDateTime = DateTime.Now.ToString()

        };
        string obj1 = JsonConvert.SerializeObject(obj);

        var query = client.CreateDocumentQuery<Class1>(
            UriFactory.CreateDocumentCollectionUri("testDb", "testDocumentCollection"))
           .Where(jo => jo.Name.Equals(name))
            .AsEnumerable().FirstOrDefault();


        if (query == null)
        {

            var document1 = await client.CreateDocumentAsync(
                            UriFactory.CreateDocumentCollectionUri("testDb", "testDocumentCollection"),
                            obj);

        }

【问题讨论】:

    标签: c# azure azure-functions azure-cosmosdb


    【解决方案1】:

    要更新文档,您必须使用 Upsert 方法:
    DocumentClient.UpsertDocumentAsync Method

    这篇博文有一些关于它的细节:
    DocumentDB: To create, or not to create, that is the question

    【讨论】:

    • upsert 就是这样做的方法
    • 我使用了 upsert 但不是更新现有文件,而是创建一个新文件
    • @Aman 您的 JSON 文档是否包含现有文档的 ID? var docSpec = new { id = "文档 id", foo = "bar" };
    • 但是name 不是id。您在 CosmosDB 中的重复条目是否具有相同的 id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多