如何在Cosmos DB中对嵌套数组执行Patch更新操作?
Cosmos DB嵌套数组Patch更新问题及解决方案
问题背景
使用Cosmos DB的PatchItemAsync更新一级数组项时可正常工作,代码示例:
ItemResponse<Lesson> response = await container.PatchItemAsync<Lesson>( id: lesson.Id, partitionKey: partitionKey, patchOperations: new[] { PatchOperation.Set<Dialog>($"/dialogs/{dialog.OriginalIndex}", dialog) });
但尝试更新嵌套数组(Lesson包含Dialog数组,每个Dialog又包含Subdialogs数组)的子项时,执行以下代码后返回状态码正常,结果却不符合预期:
ItemResponse<Lesson> response = await container.PatchItemAsync<Lesson>( id: lesson.Id, partitionKey: partitionKey, patchOperations: new[] { PatchOperation.Set<Dialog> ($"/dialogs/{parentDialog.OriginalIndex}/subdialogs/{dialog.OriginalIndex}/", dialog) });
错误表现为:未替换目标子项,反而在对应数组项中新增了一个空键属性:
"subdialogs": [ { "id": "TESTMIC-COULDNOTHEARYOU", "regenerateAudio": true, "isMessageSSML": false, "messages": [ "This is the message." ], // 新增的异常空键属性 "": { "id": "TESTMIC-COULDNOTHEARYOU", "regenerateAudio": false, "isMessageSSML": false, "messages": [ "This is the message" ] } } ]
已确认数组索引正确,需解决嵌套数组的正确Patch更新方式。
错误原因
问题出在Patch路径末尾多了一个斜杠/。Cosmos DB的JSON Patch路径遵循RFC 6901规范,末尾带斜杠时,会被解析为给目标对象添加空名称属性,而非替换数组指定索引项。
正确实现方式
只需移除Patch路径末尾的斜杠,即可准确定位并替换嵌套数组的目标子项:
ItemResponse<Lesson> response = await container.PatchItemAsync<Lesson>( id: lesson.Id, partitionKey: partitionKey, patchOperations: new[] { PatchOperation.Set<Dialog>($"/dialogs/{parentDialog.OriginalIndex}/subdialogs/{dialog.OriginalIndex}", dialog) });
此写法可正确替换subdialogs数组中指定索引的项,不会产生多余的空键属性。
内容的提问来源于stack exchange,提问作者Greg Gum
相关产品推荐
相关产品推荐

