当我需要使用MongoDB上的aggregate
命令按日期汇总内容时,我通常会这样做:
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
和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
和year
是整数。所以,我的问题是:我可以使用$project
操作键入一个字段吗?
答案 0 :(得分:6)
是,您可以使用$substr
将数字转换为字符串。您丢失的链接如下所示:
{
$project: {
day_s: { $substr: [ "$day", 0, 2 ] },
mon_s: { $substr: [ "$month", 0, 2 ] },
year_s: { $substr: [ "$year", 0, 4 ] }
}
}