您可以先使用“addFields”阶段将“created_at”时间戳转换为日期,
{
$addFields: {
convertedDate: {"$toDate":"$created_at"}
}
}
之后,您可以进行进一步的操作。所以最后你的聚合查询将是这样的,
对于 3.6 版
[
{
'$project': {
"convertedDate": { "$add": [ new Date(0), "$created_at" ] }
}
},
{
'$project': {
'month': {
'$month': '$convertedDate'
},
'year': {
'$year': '$convertedDate'
}
}
}, {
'$group': {
'_id': {
'month': '$month',
'year': '$year'
},
'total': {
'$sum': 1
},
'month': {
'$first': '$month'
},
'year': {
'$first': '$year'
}
}
}
]
对于版本 4+
[
{
'$addFields': {
'convertedDate': {"$toDate":"$created_at"}
}
},
{
'$project': {
'month': {
'$month': '$convertedDate'
},
'year': {
'$year': '$convertedDate'
}
}
}, {
'$group': {
'_id': {
'month': '$month',
'year': '$year'
},
'total': {
'$sum': 1
},
'month': {
'$first': '$month'
},
'year': {
'$first': '$year'
}
}
}
]