使用聚合将多个数据一起推送到MongoDB $ group中

时间:2019-05-27 11:59:24

标签: php mongodb aggregate

我有此mongodb数据,我想在其中group上特定date上的所有数据。然后将特定日期的数据推送到数组中。

例如:

我的收藏集中有以下数据

[
  {
    _id: {
      date: "2019-05-07",
      employee_id: {
        $oid: "5c6cfef83741401c716ff893"
      }
    },
    count: 368
  },
  {
    _id: {
      date: "2019-05-05",
      employee_id: {
        $oid: "5c6cfef83741401c716ff893"
      }
    },
    count: 282
  },
  {
    _id: {
      date: "2019-05-07",
      employee_id: {
        $oid: "5c6cfef83741401c716ff88d"
      }
    },
    count: 200
  },
  {
    _id: {
      date: "2019-05-05",
      employee_id: {
        $oid: "5c6cfef83741401c716ff87a"
      }
    },
    count: 1305
  }
]
那我的输出应该是->

[
  {
    date: "2019-05-05",
    data: [
      {
        employee_id: {
          $oid: "5c6cfef83741401c716ff893"
        },
        count: 282
      },
      {
        employee_id: {
          $oid: "5c6cfef83741401c716ff87a"
        },
        count: 1305
      }
    ]
  },
  {
    date: "2019-05-07",
    data: [
      {
        employee_id: {
          $oid: "5c6cfef83741401c716ff893"
        },
        count: 368
      },
      {
        employee_id: {
          $oid: "5c6cfef83741401c716ff88d"
        },
        count: 200
      }
    ]
  }
]

到目前为止,我已经尝试过了,但是结果格式不正确,我也不确定这是否是正确的方法。

[
  '$group'=>[
    '_id'=>'$_id.date',
    'employee_id'=>[
      '$push'=>'$_id.employee_id'
    ],
    'count'=>[
      '$push'=>'$count'
    ]
  ]
],
[
  '$project'=>[
    'data'=>[
      '$zip'=>[
        'inputs'=>[
          '$employee_id',
          '$count'
        ]
      ]
    ],
    
  ]
],

0 个答案:

没有答案