当您将 UNIX 时间存储为时间戳时,如何按月对过去 12 个月的文档进行分组?
我有一个集合,其中数据每天根据 UNIX 纪元时间更新。例如:
{
"uID" : "12345678",
"midNightTimeStamp" : NumberInt(1645381800), // 21st Feb 2022 midnight IST
"energyConsumed" : NumberInt(53)
},
{
"uID" : "12345678",
"midNightTimeStamp" : NumberInt(1645641000), // 24th Feb 2022 midnight IST
"energyConsumed" : NumberInt(30)
}
现在,如果您想按月查询过去 12 个月的数据,您会采取什么方法来解决这个问题?我所知道的是,我可以将我的数据分组到聚合查询中,如下所示:
$project: {
energyConsumed: 1.0,
year: {
$year: // How would you convert this from epoch
},
month: {
$month: // How would you convert this from epoch
}
},
现在,如果我想将过去 12 个月的数据分组为如下所示
$group: {
_id: '$month',
energyConsumed: {
$sum: '$energyConsumed'
}
}
,我想要的输出将是:
{
id: 04 // (something like 04 or just April but data should be sorted month and year wise April 2021),
energyConsumed: 4179772
},
{
id: 05 // (something like 05 or just May but data should be sorted month and year wise),
energyConsumed: 6179772
},
...
...
{
id: 03 // (something like 03 or just March (March 2022),
energyConsumed: 5643772
}
I have a collection where data is updated daily based on unix epoch time. For example:
{
"uID" : "12345678",
"midNightTimeStamp" : NumberInt(1645381800), // 21st Feb 2022 midnight IST
"energyConsumed" : NumberInt(53)
},
{
"uID" : "12345678",
"midNightTimeStamp" : NumberInt(1645641000), // 24th Feb 2022 midnight IST
"energyConsumed" : NumberInt(30)
}
Now if you wanted to query last 12 months data month wise, what would have been your approach to solve this? All I know is that I could group my data in aggregation query something like this:
$project: {
energyConsumed: 1.0,
year: {
$year: // How would you convert this from epoch
},
month: {
$month: // How would you convert this from epoch
}
},
Now if I wanted to group my data from last 12 months as something like this
$group: {
_id: '$month',
energyConsumed: {
$sum: '$energyConsumed'
}
}
And my desired output will be:
{
id: 04 // (something like 04 or just April but data should be sorted month and year wise April 2021),
energyConsumed: 4179772
},
{
id: 05 // (something like 05 or just May but data should be sorted month and year wise),
energyConsumed: 6179772
},
...
...
{
id: 03 // (something like 03 or just March (March 2022),
energyConsumed: 5643772
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许是这样的:
解释:
$group 基于由 midNightTimeStamp 字段提取的年月 ("YYYY-mm" ) 和 $sum 每月消耗
游乐场
Maybe this:
Explained:
$group based on Year-Month ("YYYY-mm" ) extracted by the midNightTimeStamp field and $sum the monthly consumption
playground
要捕获从现在开始的最后 12 个月,请将其放在上面的
$group
阶段之前:To catch just the last 12 months from right now, throw this in front of the
$group
stage above:如果您已经运行 MongoDB 5.0 版,则可以使用 $dateTrunc :
由于
timezone
选项,它可能比$dateToString: { format: "%Y-%m" ...
更精确。If you run already MongoDB version 5.0 then you can use $dateTrunc:
It might be more precise than
$dateToString: { format: "%Y-%m" ...
due totimezone
option.