Azure CosmosDB:函数应用程序 - 如何更新文档

Azure CosmosDB: function app- how to update a document

我是 Azure 的新手。我想知道是否可以通过 https 触发器获得更新现有记录的帮助。

我在网上找到的许多解决方案都是创建新记录或更新完整文档。我只想更新文档中的 2 个属性。

I tried [this][1] and the following code but it didn't work
    [FunctionName("Function1")]
    public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
       [DocumentDB("MyDb", "MyCollection", ConnectionStringSetting = "MyCosmosConnectionString")] out dynamic document,
       TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");
    
        dynamic data = req.Content.ReadAsAsync<object>().GetAwaiter().GetResult();
        document = data;
    
        return req.CreateResponse(HttpStatusCode.OK);
    }

我想传递主键和文档可以根据主字符串更新的其他 2 个值。有人可以帮忙吗?

I just want to update 2 properties in the document.

到 2020/10/20,此功能仍不支持。你可以在这个地方查看进度:

https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/6693091-be-able-to-do-partial-updates-on-document#{toggle_previous_statuses}

该功能的支持工作从一年前就开始了,现在还没有完成,我们只能等待。

你这边需要拿到文档,改内部再更新

一个简单的例子:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Azure.Cosmos;
using System.Collections.Generic;

namespace FunctionApp21
{
    public static class Function1
    {
        private static CosmosClient cosmosclient = new CosmosClient("AccountEndpoint=https://testbowman.documents.azure.com:443/;AccountKey=xxxxxx;");
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            CosmosContainer container = cosmosclient.GetContainer("testbowman", "testbowman");

            ItemResponse<ToDoActivity> wakefieldFamilyResponse = await container.ReadItemAsync<ToDoActivity>("testbowman", new PartitionKey("testbowman"));
            ToDoActivity itemBody = wakefieldFamilyResponse;

            itemBody.status = "This is been changed.";
            wakefieldFamilyResponse = await container.ReplaceItemAsync<ToDoActivity>(itemBody, itemBody.id, new PartitionKey(itemBody.testbowman));
            return new OkObjectResult("");
        }
    }
    public class ToDoActivity
    {
        public string id { get; set; }
        public string status { get; set; }

        public string testbowman { get; set; }
    }
}

官方文档:

https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-dotnet-v4#replace-an-item