我正在尝试使用Mongo聚合框架按日期对文档进行分组。我尝试了很多东西,但无法识别问题。我的查询如下所示:
// get current date and then get the date 8 months ago
var now = Date.now()
var lastMonth = 60*60*24*30*1000*8
lastMonth = now - lastMonth
var query = {
type: 'something',
deleted: {$ne: true},
created: {$gte: lastMonth}
}
var stickerNames = [];
db.Message.aggregate([{$match: query},
{$group:
{_id: {data: '$data',
month: {$month: '$created'},
year: {$year: '$created'}
},
count:{$sum: 1}
}
},
{$sort:
{count: 1}}],
function(err, stuff){
if(err){
return res.json({error: err.message})
}
else{
return res.json({data: stuff})
}
})
我用日期尝试了很多不同的东西,并检查了其他SO的帖子,但到目前为止没有任何效果。如果我取出创建的:{$gte: lastMonth}子句,它会返回每个“某样东西”类型的文档。如果我离开它,它不会返回任何文档。
创建的字段在模型中设置为
created: {type: Date, default: Date.now}
据我理解,“按日期分组”的意思是按“日-月-年”分组。也许你错过了$dayOfMonth
聚合功能?
给定此示例数据集:
> db.w.find({})
{ "_id" : ObjectId("55503d31a3d32cf6295ad897"),
"created" : ISODate("2014-12-08T12:00:00Z"),
"data" : 1 }
{ "_id" : ObjectId("55503d43a3d32cf6295ad898"),
"created" : ISODate("2014-12-08T08:00:00Z"),
"data" : 2 }
{ "_id" : ObjectId("55503d4ba3d32cf6295ad899"),
"created" : ISODate("2014-12-08T20:00:00Z"),
"data" : 3 }
{ "_id" : ObjectId("55503d55a3d32cf6295ad89a"),
"created" : ISODate("2014-12-06T20:00:00Z"),
"data" : 4 }
{ "_id" : ObjectId("55503d77a3d32cf6295ad89c"),
"created" : ISODate("2015-12-08T20:00:00Z"),
"data" : 5 }
以及该聚合管道:
> db.w.aggregate([
{$group:
{
_id:
{
day: {$dayOfMonth: "$created"},
month: {$month: "$created"},
year: {$year: "$created"}
},
total: {$sum: "$data"},
count: {$sum: 1}
}
},
{$sort: {count: 1}}
])
您将获得预期的结果:
{ "_id" : { "day" : 8, "month" : 12, "year" : 2015 }, "total" : 5, "count" : 1 }
{ "_id" : { "day" : 6, "month" : 12, "year" : 2014 }, "total" : 4, "count" : 1 }
{ "_id" : { "day" : 8, "month" : 12, "year" : 2014 }, "total" : 6, "count" : 3 }