如何将对象映射到查询中的数组

时间:2016-04-12 15:11:20

标签: arangodb

假设我有一个名为“repos”的集合,其中包含类似这样的对象:

{
  name: 'myrepo',
  actions: [
     { timestamp: '2016-04-12T14:43:20Z', change: 'add' },
     { timestamp: '2016-04-12T14:45:10Z', change: 'remove' },
     { timestamp: '2016-04-12T15:03:03Z', change: 'add' },
     ... and so on ....
  ]
}

现在我想要一个查询将这些对象转换成这样的东西:

{
   name: 'myrepo',
   timestamps: ['2016-04-12T14:43:20Z', '2016-04-12T14:45:10Z', '2016-04-12T15:03:03Z'],
   changes: ['add', 'remove', 'add']
}

我想到了以下内容:

FOR r in repos
LET changes= (FOR a IN r.actions RETURN a.change )
LET timestamps = (FOR a IN r.actions RETURN a.timestamp)
RETURN {
    name: r.name,
    changes: changes,
    timestamps: timestamps
    }

但我担心双重FOR可能效率不高。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您可以使用array expansion operator

以更紧凑的形式表达您的查询
FOR r IN repos RETURN {
  name: r.name,
  changes: r.actions[*].change,
  timestamps: r.actions[*].timestamp
}

您也可以使用UNIQUE仅为结果中的每条记录获取一次更改类型(如果数组changestimestamps不必排队):< / p>

FOR r IN repos RETURN {
    name: r.name,
    changes: UNIQUE(r.actions[*].change),
    timestamps: r.actions[*].timestamp
}

通常,您的查询只会增加两个子查询的开销,并且不应该比上面的查询慢得多。但是,它更紧凑,因此读起来更好一点,不是吗?