MongoDB:使用新键将键和值作为单独的数组获取

MongoDB: Get keys and values as separate arrays with new keys

我有以下 MongoDB collection.

{
    "timestamp": "10:05:12",
    "value": 100
},
{
    "timestamp": "15:07:01",
    "value": 120
}, ... 

注意:此处“...”表示相同结构的更多数据。

预期结果

{
    "timestamps" : ["10:05:12", "15:07:01", ...],
    "values": [100, 120, ...]
}
  1. $group - 按 null 分组并使用 $pushtimestampvalue 添加到 timestampsvalues数组。
db.collection.aggregate([
  {
    $group: {
      _id: null,
      timestamps: {
        $push: "$timestamp"
      },
      values: {
        $push: "$value"
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])

Sample Mongo Playground