mongodb聚合按日期获取所有字段和组

mongodb聚合按日期获取所有字段和组,mongodb,aggregation-framework,Mongodb,Aggregation Framework,收藏 { "_id" : ObjectId("5a143a79ca78479b1dc90161"), "createdAt" : ISODate("2017-11-21T14:38:49.375Z"), "amount" : 227.93359186, "pair" : "ant_eth" } 预期产量 { "12-12-2012": [ { "pair": "ant_eth", "sum": "sum of amounts in

收藏

{
    "_id" : ObjectId("5a143a79ca78479b1dc90161"),
    "createdAt" : ISODate("2017-11-21T14:38:49.375Z"),
    "amount" : 227.93359186,
    "pair" : "ant_eth"
}
预期产量

{
  "12-12-2012": [
    {
     "pair": "ant_eth",
     "sum": "sum of amounts in 12-12-2012"
    },
    {
     "pair": "new_pair",
     "sum": "sum of amounts in 12-12-2012"
    },
  ],
  "13-12-2012": [{
    "pair": "ant_eth",
    "sum": "sum of amounts in 13-12-2012"
  }]
}
迄今为止,我所取得的成就与我所知相去甚远

const criteria = [
  { $group: { 
    _id: '$pair', 
    totalAmount: { $sum: '$amount' } } }
]

任何有助于实现预期产出的帮助都是非常感谢的

这就是我能做到的:

db.collection.aggregate([{
    $group: {
        _id: {
            year: {
                "$year": "$createdAt"
            },
            month: {
                "$month": "$createdAt"
            },
            day: {
                "$dayOfMonth": "$createdAt"
            },
            pair: "$pair"
        },
        sum: {
            $sum: "$amount"
        }
    }
}])

接下来,您可能需要进行应用程序端解析,以生成所需的输出。好的,因此您只需要按datetime和datetime对的日期部分求和金额,然后“组织”所有对+按日期求和。您可以通过如下所示的“重新组合”来实现这一点。第一个
$group
创建总和,但留下重复的日期。第二个
$group
将输出修复为几乎符合您的要求,只是日期保留为
\u id
的RVAL,而不是变为lvals(字段名)

db.foo.aggregate([
  {
    $group: {
      _id: {d: {$dateToString: { format: "%Y-%m-%d", date: "$createdAt"}}, pair: "$pair"}, 
       n: {$sum: "$amount"}
    }
  },
  {
    $group: {
      _id: "$_id.d", 
      items: {$push: {pair: "$_id.pair", sum: "$n"}} 
    }
  }
]);
如果您确实想要字段名,那么在第二个
$group
之后添加这两个阶段:

,{$project: {x: [["$_id","$items"]] }}
,{$replaceRoot: { newRoot: {$arrayToObject: "$x"} }}