由于mongodb中的ISODate时间比北京时间相差了8个小时。因此在做统计的时候根据时间查询的时候就需要把这个时间加起来才可以。代码如下:
以下是node.js的写法
Collection.aggregate({
$match: {
$and: [{ entertime: { '$gte': new Date("2016-01-01"), '$lte': new Date("2016-12-31") } }, { exittime: { '$gte': new Date("2016-01-01"), '$lte': new Date("2016-12-31") } }]
}
},
{
$group: {
_id: {
year: { $year: { $add: ['$exittime', 28800000] } },//时间在分组前会加上8个小时
month: { $month: { $add: ['$exittime', 28800000] } },
day: { $dayOfMonth: { $add: ['$exittime', 28800000] } }
},
num_tutorial: { $sum: 1 }
}
},
function (err, groupByRecords) {
if (err) {
next(err);
} else {
for (var j = 1; j <= deaddate; j++) {
count = 0;
for (var i = groupByRecords.length; i >= 1; i--) {
if (parseInt(groupByRecords[i - 1]._id.day) == j && groupByRecords[i - 1]._id.month == cmonth) {
count = groupByRecords[i - 1].num_tutorial;
break;
}
}
m.push(j);
c.push(count);
}
t.m = m;
t.c = c;
res.json(t);
}
});