【发布时间】:2017-06-23 22:10:51
【问题描述】:
这是我的收藏的样子...
{
"_id" : ObjectId("53c66071409aeb38133c6ece"),
"starttime" : ISODate("2014-07-15T11:22:25Z"),
"product" : "1",
"customer" : "Microsoft"
}
{
"_id" : ObjectId("53c66071409aeb38133c6ecf"),
"starttime" : ISODate("2014-07-15T11:22:25.882Z"),
"customer" : "Microsoft",
}
{
"_id" : ObjectId("53c66072409aeb38133c6ed0"),
"starttime" : ISODate("2014-07-16T11:22:26.15Z"),
"customer" : "Microsoft",
}
{
"_id" : ObjectId("53c66072409aeb38133c6ed0"),
"starttime" : ISODate("2014-07-16T11:22:27.15Z"),
"customer" : "Apple",
}
我想按日期对数据进行分组 并格式化输出,使其显示如下......(我已经对我所缺少的内容发表了评论)
[
{
"_id": {
"date": {
"year": 2014,
"month": 7,
"day": 16
}
},
"productions": [
{
"name": "Microsoft",
"number": 1 //THIS IS MISSING AT THE MOMENT
},
{
"name": "Apple",
"number": 1 //THIS IS MISSING AT THE MOMENT
}
],
"total": 2
},
{
"_id": {
"date": {
"year": 2014,
"month": 7,
"day": 15
}
},
"productions": [
{
"name": "Microsoft",
"number": 2 //THIS IS MISSING AT THE MOMENT
}
],
"total": 2
}
]
我按照问题groups by month and year using mongoose.js的答案 我非常接近解决这个问题,但并不完全在那里。我现在已经到了只见树木不见森林的地步!
这是我目前的代码...
Job.aggregate({
$project: {
date: {
year: {
$year: "$starttime",
},
month: {
$month: "$starttime"
},
day: {
$dayOfMonth: "$starttime"
}
},
customer: "$customer",
}
}, {
$group: {
_id: {
date: {
year: "$date.year",
month: "$date.month",
day: "$date.day"
},
},
productions: {
$addToSet: {
name: "$customer",
},
},
total: {
$sum: 1
}
},
},
function(error, customers) {
if (error) res.json(error);
res.json(customers);
})
缺少的是每个日期的“生产数量”总数。我只是得到日期总数。 有人可以告诉我哪里出错了吗?我会非常感激。谢谢。
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework