MongoDB聚合:如何使用$ project重新组合日期?

Isa*_*ell 10 mongoose mongodb

我正在尝试按天聚合我的数据,以便我可以在图表中呈现它.我已经成功地通过分组成功地做到这一点$year,$month$dayOfMonth.但是,这意味着我的日期现在在最终结果中分为三个部分.有没有办法将这三个数字连接成日期格式,还是有另一种方法可以按日分组,而不是分割日期?以下是我所拥有的一个工作示例:

Sentiment.aggregate([
    {
        $match: { 'content.term' : term_id }
    }, {
        $group: {
            _id: {
                year       : { $year       : '$created_at' },
                month      : { $month      : '$created_at' },
                dayOfMonth : { $dayOfMonth : '$created_at' },
            },
            sum   : { $sum : '$score'},
            count : { $sum : 1 }
        },
    }, {
        $project: {
            _id   : 0,
            date  : '$_id',
            sum   : 1,
            count : 1,
            avg   : { $divide: ['$sum', '$count'] }
        }
    }
], function(err, result){
    if(err) callback(err);
    else callback(null, result);
});
Run Code Online (Sandbox Code Playgroud)

这是一个示例结果:

[
  {
    "sum": 201,
    "count": 3,
    "date": {
      "year": 2013,
      "month": 7,
      "dayOfMonth": 5
    },
    "avg": 67
  },
  {
    "sum": 186,
    "count": 6,
    "date": {
      "year": 2013,
      "month": 7,
      "dayOfMonth": 8
    },
    "avg": 31
  },
  {
    "sum": 834,
    "count": 9,
    "date": {
      "year": 2013,
      "month": 7,
      "dayOfMonth": 9
    },
    "avg": 92.66666666666667
  }
]
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想date成为一个有效的日期,所以我不必在以后转换它.我尝试过使用$concat但只适用于字符串.我正在使用,Mongoose如果这有所作为.

小智 19

假设,因为你是通过分组年,月,日的文件,小时和分钟是没有用的,你可以使用这些运营商之一获得一个约会样本:$first,$last,$min$max.

Sentiment.aggregate([
    {
        $match: { 'content.term' : term_id }
    }, {
        $group: {
            _id: {
                year       : { $year       : '$created_at' },
                month      : { $month      : '$created_at' },
                dayOfMonth : { $dayOfMonth : '$created_at' },
            },
            dt_sample : { $first : '$created_at' },
            sum   : { $sum : '$score'},
            count : { $sum : 1 }
        },
    }, {
        $project: {
            _id   : 0,
            date  : '$dt_sample',
            sum   : 1,
            count : 1,
            avg   : { $divide: ['$sum', '$count'] }
        }
    }
], function(err, result){
    if(err) callback(err);
    else callback(null, result);
});
Run Code Online (Sandbox Code Playgroud)

您将拥有一个具有任意小时,分钟和秒的日期字段.