gpt4 book ai didi

c# - 如何更新cosmos db中的子文档

转载 作者:太空狗 更新时间:2023-10-30 00:48:04 25 4
gpt4 key购买 nike

我是 Cosmos Db 新手,想了解如何删除/更新插入文档集合中的子文档。

如果我有一个文档:


{
"Id": "1234",
"Name": "foo",
"Items": [
{
"Id": "abcd",
"Age": 35,
"Claims": [
{
"Name": "email",
"Value": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50363f3f103231227e333f3d" rel="noreferrer noopener nofollow">[email protected]</a>"
}
]
}
]
}

我该怎么做:

1) 将项目添加到文档的项目列表中。

2) 从项目列表中删除现有项目

3) 将项目更新插入文档中的项目列表

4) 向项目列表中的现有项目添加/删除声明值?

提前致谢。

最佳答案

正如 @Sajeetharan 所说,azure cosmos db 现在不支持部分更新。看来团队正在积极致力于此功能。现在,您可以在存储过程中更新整个文档。

示例代码如下供引用:

function updateSproc(id, update) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();

tryQueryAndUpdate();

function tryQueryAndUpdate(continuation) {
var query = {query: "select * from root r where r.id = @id", parameters: [{name: "@id", value: id}]};
var requestOptions = {continuation: continuation};

var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
if (err) throw err;

if (documents.length > 0) {
tryUpdate(documents[0]);
} else {
throw new Error("Document not found.");
}
});
}

function tryUpdate(document) {
var requestOptions = {etag: document._etag};

var fields, i;

fields = Object.keys(update);
for (i = 0; i < fields.length; i++) {
document[fields[i]] = update[fields[i]];
}

var isAccepted = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) {
if (err) throw err;
response.setBody(updatedDocument);
});
}

但是,Azure Cosmos DB 支持 MongoDB 协议(protocol)。您可以在Azure official page上确认支持的功能。 .

因此,支持增量操作。请引用这个link .

希望对您有帮助。如有任何疑问,请随时告诉我。

关于c# - 如何更新cosmos db中的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50244543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com