簡體   English   中英

如何使用 c# 更新 cosmos db 文檔

[英]How to update cosmos db document using c#

如果文件名已經存在,我想更新 cosmos DB 中的文檔。 為此,我傳遞了一個將帶來結果的查詢,我想更新該結果。 我想將修改日期設置為它。 如果它是新創建的,如果它已經存在,則添加修改日期。
我面臨更新它的問題,這將在其他部分出現。
這是我的代碼片段:

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

        }

要更新文檔,您必須使用 Upsert 方法:
DocumentClient.UpsertDocumentAsync 方法

這個博客條目有一些關於它的細節:
DocumentDB:創建還是不創建,這是個問題

要更新,您需要閱讀整個文檔並再次將其保存到集合中。 如果您想更新當前不支持的某些字段。

如果要進行complete document replacement ,可以使用 UpsertDocumentAsync 方法,如下所示。

    {
        var client = new DocumentClient(new Uri(ConfigurationHelper.GetCosmosDbEndpointUri()), ConfigurationHelper.GetCosmosDbPrimaryKey());
        await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName), document);
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: {0}, Message: {1}", e.Message, e.GetBaseException().Message);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM