更新时间: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
}