【问题标题】:ArangoDB: Join with nested object collection keysArangoDB:使用嵌套对象集合键加入
【发布时间】:2020-11-09 09:49:16
【问题描述】:

在 ArangoDB 连接查询方面需要一些帮助。我有如下文档,其中用户包含嵌套对象(groups) 中的组集合键。当我查询用户时,我需要加入组集合并更改响应。应该只做WITH QUERY。请查看下面给出的示例以获得更清晰的信息。

// User Collection
[
  {
    _key: "312121"
    name: "Ash",
    groups: {
      "1": ["323223", ...etc], // Group collection _keys;
      "2": ["342323", ...etc] // Group collection _keys;
    } 
  }
]

// Group Collection
[
  {
    _key: "323223"
    name: "Group 1"
  },
  {
    _key: "313131"
    name: "Group 2"
  }
]

我试过这个查询:

LET user = DOCUMENT('users/312121')
LET groups_keys = ATTRIBUTES(user.groups) // ["1", "2"]
LET list = (
  FOR key IN groups_keys
  LET groups = (
     FOR group_key IN user.groups[key] // user.groups["1"] and so on..
     LET group = DOCUMENT(CONCAT('groups/', group_key))
     RETURN { group_id: group._key, name: group.name }
  )
  RETURN { [key]: groups }
)

RETURN MERGE(user, { groups: groups })

它将groups 返回为Array,但需要groups 成为Object

// Current Output: 
{
  _key: "312121"
  name: "Ash",
  groups: [ // <-- This should be object, not an array
    {
      "1": [{ _key: "323223", name: "Group 1" }]
    },
    {
      "2": [{ _key: "313131", name: "Group 2" }]
    }
  ]
}

但它应该是这种格式:

// Expected Output:

{
  _key: "312121"
  name: "Ash",
  groups: { // <-- like this
    "1": [{ _key: "323223", name: "Group 1" }],
    "2": [{ _key: "313131", name: "Group 2" }]
  }
}

非常感谢您的帮助!

【问题讨论】:

    标签: node.js arangodb arangojs


    【解决方案1】:

    使用MERGE

    MERGE [docs] 也接受一个数组参数:

    LET list = MERGE(
      /* omitted */
      RETURN { [key]: groups }
    )
    

    使用ZIP

    替代解决方案也可以使用ZIP [docs]:

    LET list = (
      /* omitted */
      RETURN { key, groups } // Notice the format
    )
    LET obj = ZIP(list[*].key, list[*].groups)
    

    【讨论】:

    • 感谢您的回复,我想我已经尝试过 MERGE 和 ZIP,会再尝试一次并告诉您。
    • ZIP 为我工作。谢谢布鲁!!,我确实尝试过,但错过了RETURN { key, groups}。无论如何,非常感谢!
    • @Naren 我很高兴你成功了!我将更新答案以强调 sn-p 的那一部分。
    【解决方案2】:

    试试这个希望对你有帮助

    const newObject = {};
    for (const [key, value] of Object.entries(grouped)) { 
      newObject[value[0].<your choice of key or>] = value
    }
    

    【讨论】:

    • 感谢您的回复,但这应该仅限于 QUERY。否则,我们可以使用Array.reduce
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 2021-11-05
    • 2020-12-27
    • 1970-01-01
    • 2014-05-18
    • 2019-12-31
    • 1970-01-01
    相关资源
    最近更新 更多