【发布时间】:2015-02-06 14:14:34
【问题描述】:
我有一个预订表,我想获得一个月内的预订数量,即按月分组。
我很困惑如何从日期中获取月份。
这是我的架构:
{
"_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 }
我哪里错了?
【问题讨论】:
-
"bookingdatetime" : "2012-10-11T07:00:00Z" 是字符串吗?
-
您需要将其转换为 ISODate,然后对其进行聚合。否则,使用 Map/Reduce
-
使用 new Date($bookingdate) 将字符串转换为 ISODate。 new Date("2012-10-11T07:00:00Z") 这是输出 ISODate("2012-10-11T07:00:00Z")
-
我有这个查询:db.booking.aggregate({$project: {month:{$month:new Date("$bookingdatetime")}}}, {$group:{_id: {month:"$month"},numberofbookings:{$sum:1}}} 但它给了我错误的输出:{ "_id" : { "month" : 8 }, "numberofbookings" : 3 }