我正在尝试按日期将文档与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帖子,但到目前为止没有任何工作。如果我取出created:{$ gte:lastMonth}子句,那么它将返回'something'类型的每个文档。如果我离开它,它不会返回任何文件。
创建的字段在模型中按
设置created: {type: Date, default: Date.now}
答案 0 :(得分:2)
据我所知,"按日期分组"表示分组日期"日 - 月 - 年"。也许您错过了$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 }