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

how to map objects into arrays in a query

假设我有一个名为 "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效率不是很高

有什么建议吗?

您可以使用 array expansion operator:

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

您也可以使用 UNIQUE 只获取结果中每条记录一次的每种更改类型(如果数组 changestimestamps 不必排列):

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

一般来说,你的查询只增加了两个子查询的开销,应该不会比上面慢多少。但是,它更紧凑,因此更易读,不是吗?