是否可以在MongoDB上的聚合管道中键入转换数据?

时间:2014-02-11 12:02:11

标签: mongodb aggregation-framework

当我需要使用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}
        }
    }
 )

并最终将daymonyear字段连接到应用程序中的日期字符串中。但是出于很多原因,有时我想在离开数据库之前连接字段,所以我最初尝试过:

 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期望字符串,daymonyear是整数。所以,我的问题是:我可以使用$project操作键入一个字段吗?

1 个答案:

答案 0 :(得分:6)

,您可以使用$substr将数字转换为字符串。您丢失的链接如下所示:

{
    $project: {
        day_s:  { $substr: [ "$day",   0, 2 ] }, 
        mon_s:  { $substr: [ "$month", 0, 2 ] }, 
        year_s: { $substr: [ "$year",  0, 4 ] }
    }
}