use*_*763 5 mongoose mongodb node.js
我正在尝试在MongoDB中进行每日聚合.我已经有一个聚合,我按天成功地对数据进行分组.但是,我想以这样的方式进行聚合,在这种情况下,没有数据显示的日期是空的.也就是说,它们是空箱.
以下是我到目前为止的情况.我无法在MongoDB文档中找到任何内容,或者建议如何进行聚合并生成空箱:
app.models.profile_view.aggregate(
{ $match: { user: req.user._id , 'viewing._type': 'user' } },
{ $project: {
day: {'$dayOfMonth': '$start'},month: {'$month':'$start'},year: {'$year':'$start'},
duration: '$duration'
} },
{ $group: {
_id: { day:'$day', month:'$month', year:'$year' },
count: { $sum: 1 },
avg_duration: { $avg: '$duration' }
} },
{ $project: { _id: 0, date: '$_id', count: 1, avg_duration: 1 }}
).exec().then(function(time_series) {
console.log(time_series)
return res.send(200, [{ key: 'user', values: time_series }])
}, function(err) {
console.log(err.stack)
return res.send(500, { error: err, code: 200, message: 'Failed to retrieve profile view data' })
})
Run Code Online (Sandbox Code Playgroud)
我不认为您将能够使用聚合解决此问题.当您使用$ group时,mongo只能根据您提供的数据进行分组.在这种情况下,mongo将如何知道缺少哪些日期值,甚至知道可接受日期的范围是多少?
我认为您最好的选择是将缺少的日期值添加到聚合的结果中.
| 归档时间: |
|
| 查看次数: |
1252 次 |
| 最近记录: |