且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按月分组统计

更新时间:2023-01-29 20:38:55

您不能在聚合管道中包含任意JavaScript,因此,因为您将bookingdatetime存储为string而不是Date,所以不能使用$month运算符。

但是,由于日期字符串遵循严格的格式,您可以使用$substr运算符从字符串中提取月份值:

db.test.aggregate([
    {$group: {
        _id: {$substr: ['$bookingdatetime', 5, 2]}, 
        numberofbookings: {$sum: 1}
    }}
])

输出:

{
    "result" : [ 
        {
            "_id" : "03",
            "numberofbookings" : 1
        }, 
        {
            "_id" : "07",
            "numberofbookings" : 1
        }, 
        {
            "_id" : "10",
            "numberofbookings" : 1
        }
    ],
    "ok" : 1
}