首页 > 解决方案 > 带有 $push 的 mongo 组不允许重复键

问题描述

我有以下文件结构:

{
readings:[
{"timestamp":"1234","data":"9"},
{"timestamp":"1234","data":"90"},
{"timestamp":"12" "data":"100"}]
}

是否可以使用重复键对三个数组进行分组。

预期结果 :

{
"readings":["1234","1234","12"]
}

我的查询:

[
  {
    $group: {
      _id: "null",
      readings: {
        $push: "$readings.timestamp"
      }
    }
  }
];

但它不允许重复键。

标签: mongodbmongodb-queryaggregation-framework

解决方案


readings是一个数组,当你分组时,你会得到数组的数组。如果您readings将字段展平并对其进行分组,您将获得所需的结果。

试试这个:

db.collection.aggregate([
  {
    $unwind: "$readings"
  },
  {
    $group: {
      _id: "null",
      readings: {
        $push: "$readings.timestamp"
      }
    }
  }
])

推荐阅读