我有一个预订表,我想获得一个月内的预订数量,即按月分组。
我很困惑如何从日期中获取月份。
这是我的架构:
{
"_id" : ObjectId("5485dd6af4708669af35ffe6"),
"bookingid" : 1,
"operatorid" : 1,
...,
"bookingdatetime" : "2012-10-11T07:00:00Z"
}
{
"_id" : ObjectId("5485dd6af4708669af35ffe7"),
"bookingid" : 2,
"operatorid" : 1,
...,
"bookingdatetime" : "2014-07-26T05:00:00Z"
}
{
"_id" : ObjectId("5485dd6af4708669af35ffe8"),
"bookingid" : 3,
"operatorid" : 2,
...,
"bookingdatetime" : "2014-03-17T11:00:00Z"
}
这是我尝试过的:
db.booking.aggregate([
{ $group: {
_id: new Date("$bookingdatetime").getMonth(),
numberofbookings: { $sum: 1 }
}}
])
但它会返回:
{ "_id" : NaN, "numberofbookings" : 3 }
我哪里错了?
最佳答案
您需要在您的组中使用 $month 关键字。您的 new Date().getMonth()
调用只会发生一次,并且会尝试从字符串“$bookingdatetime”中创建一个月。
db.booking.aggregate([
{$group: {
_id: {$month: "$bookingdatetime"},
numberofbookings: {$sum: 1}
}}
]);
关于mongodb - 按月分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27366209/