gpt4 book ai didi

node.js - Mongodb按日期聚合,带有空的daybins

转载 作者:IT老高 更新时间:2023-10-28 13:34:36 25 4
gpt4 key购买 nike

我正在尝试在 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' })
})

最佳答案

我认为您无法使用聚合来解决此问题。当您使用 $group 时,mongo 只能根据您提供的数据进行分组。在这种情况下,mongo 怎么知道哪些日期值丢失了,甚至可以接受的日期范围是多少?

我认为您最好的选择是将缺失的日期值添加到聚合结果中。

关于node.js - Mongodb按日期聚合,带有空的daybins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25079352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com