是否可以在MongoDB上的聚合管道内键入强制转换数据? [英] Is it possible to type cast data inside an aggregation pipeline on MongoDB?
问题描述
当我需要使用MongoDB上的aggregate
命令按日期汇总事物时,通常会这样做:
When I need to aggregate things by date using the aggregate
command on MongoDB, I usually do this:
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
字段连接到应用程序中的日期字符串.但是由于种种原因,有时我想在离开数据库之前将这些字段连接起来,所以我最初尝试了:
and eventually concatenate the day
, mon
, and year
fields into a date string in the application. For many reasons though, sometimes I want to concatenate the fields before leaving the database, so I initially tried:
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
操作键入强制转换字段吗?
This won't work because $concat
expects strings and day
, mon
and year
are integers. So, my question is: can I type cast a field with the $project
operation?
推荐答案
是,您可以使用$substr
将数字强制转换为字符串.您缺少的链接看起来像:
Yes, you can use $substr
for casting a number to a string. Your missing link would look like:
{
$project: {
day_s: { $substr: [ "$day", 0, 2 ] },
mon_s: { $substr: [ "$month", 0, 2 ] },
year_s: { $substr: [ "$year", 0, 4 ] }
}
}
这篇关于是否可以在MongoDB上的聚合管道内键入强制转换数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!