$dateToString returns null with $group in mongodb

$dateToString returns null with $group in mongodb

我正在尝试使用 id 字段、日期时间字段进行分组,并投影值和日期字段的总和。

db.getCollection('driver_collections').aggregate([
{$group : { _id: {driverid:"$driver_id",day:{ $dayOfMonth: "$time_in"},
                  month:{$month:"$time_in"},year:{$year:"$time_in"}},
    amountCollected : {$sum:"$total_collection"}}    
    },{
       $project: {
          yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$time_in" }},
          amountCollected : 1
       }
   }]) 

我使用上面的查询得到的结果是

{
    "_id" : {
        "driverid" : "58014ce1f39e0f9dc40000b2",
        "day" : 30,
        "month" : 10,
        "year" : 2016
    },
    "amountCollected" : 2094.0,
    "yearMonthDay" : null
}

我需要将 yearMonthDay 设为

"yerMonthDay" : "2016-10-30"

当我在没有 $group 的情况下使用 $dateToString 时,它工作正常。我在这里错过了什么。

在你的第一阶段添加一个$time_in

 db.getCollection('driver_collections').aggregate([
    {$group : { _id: {driverid:"$driver_id",day:{ $dayOfMonth: "$time_in"},
                      month:{$month:"$time_in"},year:{$year:"$time_in"}},
    "time_in" : {$first : "$time_in"},
        amountCollected : {$sum:"$total_collection"}}    
        },{
           $project: {
              yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$time_in" }},
              amountCollected : 1
           }
       }])