gpt4 book ai didi

ArangoDB/AQL 更新嵌套文档

转载 作者:行者123 更新时间:2023-12-02 19:09:39 25 4
gpt4 key购买 nike

给定以下文档结构:

{
"_key": "abc",
"_id": "abc",
"label": "Company ABC",
"departments": [
{
"name": "Department 123",
"id": "123"
},
{
"name": "Department 456",
"id": "456"
}
]
}

您能告诉我为什么以下查询不起作用吗?错误消息是“缺少文档 key ”。我在另一个 SO ( ArangoDB AQL: Update single object in embedded array ) 中发现了一个更长、更复杂的解决方法,但我很好奇这个更简单的查询到底出了什么问题。

FOR c IN company
FOR d in c.deparments
FILTER d.id == “456”
UPDATE d WITH { name: “Department 789” } IN company
RETURN d

最佳答案

目前,我只知道如何更新 ArangoDB 中的顶级属性。虽然我希望将来有一些替代方案引起我的注意,但这里有一些适合您的情况的选项。

使用合并更新

在此示例中,我们通过重写数组并在满足条件时使用 MERGE 函数来更新顶级 departments 属性。

LET company = DOCUMENT("companies/abc")

UPDATE company WITH {
departments:
(FOR department IN company.departments
RETURN department.id == "456" ?
MERGE(department, {name: "Department 789"}) : department)
} IN companies

使用替代数据模型

上面的示例假设部门数据嵌入在公司文档中。考虑以下因素:

“公司”集合

{
"_key": "abc",
"_id": "companies/abc",
"label": "Company ABC"
}

“部门”集合(单独的文档)

{
"_key": "456",
"_id": "departments/456",
"company": "companies/abc",
"name": "Department 456"
}

{
"_key": "123",
"_id": "departments/123",
"company": "companies/abc",
"name": "Department 123"
}

获取公司 #ABC 及其部门:

LET company = DOCUMENT("companies/abc")

LET departments =
(FOR department IN departments
FILTER department.company == company._id
RETURN department)

RETURN MERGE(company, {departments})

结果:

{
"_id": "companies/abc",
"_key": "abc",
"label": "Company ABC",
"departments": [
{
"_key": "456",
"_id": "departments/456",
"company": "companies/abc",
"name": "Department 456"
},
{
"_key": "123",
"_id": "departments/123",
"company": "companies/abc",
"name": "Department 123"
}
]
}

更新部门#456:

LET department = DOCUMENT("departments/456")

UPDATE department WITH {name: "Department 789"} IN departments

请注意,您需要在 departments 集合中的 company 属性上添加索引。您可以在此处获取有关索引的详细信息:

https://docs.arangodb.com/3.3/Manual/Indexing/WhichIndex.html

您必须权衡这两种模型的优缺点。

关于ArangoDB/AQL 更新嵌套文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48955791/

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