ArangoDB / AQL更新嵌套文档

时间:2018-02-23 20:29:34

标签: arangodb aql

鉴于以下文件结构:

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

你能告诉我为什么以下查询不起作用吗?错误消息是“缺少文档密钥”。我在另一个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

1 个答案:

答案 0 :(得分:6)

目前,我只知道如何更新ArangoDB中的顶级属性。虽然我希望将来能引起我的注意,但这里有一些选择。

使用MERGE更新

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

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

使用替代数据模型

以上示例假设部门数据嵌入公司文档中。请考虑以下事项:

<强>&#34;公司&#34;集合

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

<强>&#34;部门&#34;集合(单独的文档)

{
  "_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

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

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

你必须权衡两种模式的优缺点。