当我需要使用按日期聚合内容时aggregate
在 MongoDB 上的命令,我通常这样做:
db.mycollection.aggregate(
{
$project: {
day: {$dayOfMonth: "$date"},
mon: {$month: "$date"},
year: {$year: "$date"},
}
},
{
$group: {
_id : {day: "$day", mon: "$mon", year: "$year"},
count: {$sum: 1}
}
}
)
并最终连接day
, mon
, and year
字段转换为应用程序中的日期字符串。但出于多种原因,有时我想在离开数据库之前连接字段,所以我最初尝试:
db.mycollection.aggregate(
{
$project: {
day: {$dayOfMonth: "$date"},
mon: {$month: "$date"},
year: {$year: "$date"},
}
},
$project: {
datestr: {
$concat : ["$year", "-", "$month", "-", "$day"]
}
}
},
{
$group: {
_id : {day: "$day", mon: "$mon", year: "$year"},
count: {$sum: 1}
}
}
)
这行不通,因为$concat
期望字符串和day
, mon
and year
是整数。所以,我的问题是:我可以使用以下命令键入强制转换字段吗$project
手术?