gpt4 book ai didi

mongodb - 按日期对 MongoDB 数据进行分组

转载 作者:可可西里 更新时间:2023-11-01 09:34:30 25 4
gpt4 key购买 nike

MongoDB 3.4 集合将包含时间戳的传感器信息存储为 ISODate 字段。

无论是在白天还是晚上,传感器信息都需要进行不同的处理,其中晚上表示 >= 20.00(晚上 8 点)和 < 08.00(上午 8 点)。我可以轻松使用 $hour检查测量值是白天还是晚上

根据要求,夜间的所有测量都属于夜晚开始的日期,即 21.00 的测量日期适合,而需要从 03.00 的测量中减去一天。

我想对所有 night 测量进行汇总($match 步骤过滤掉全天测量,这不是问题)并按日期分组夜晚。你知道我该怎么做吗?我考虑过使用 $project 步骤并获取时间信息,但不确定如何生成可用于组操作的有效 _id

最佳答案

过滤部分可以使用 $addFields来完成 管道,它还用于创建要在 $group 中使用的字段 _id 键和随后的 $match 管道。这样的 Backbone 是 $cond 运算符,它将评估需求中的条件以产生所需的日期。

单个 $redact 管道就足够了,但由于您还需要逻辑来对过滤后的文档进行分组,因此您不妨使用 $addFields 管道来创建具有这种逻辑的字段。

下面的例子演示了这个概念:

db.sensors.aggregate([
{
"$addFields": {
"yearMonthDay": {
"$cond": [
{ /* check if date hour is less than 8 */
"$lt": [
{ "$hour": "$date" },
8
]
},
{ /* subtract one day from a measurement at < 08:00 */
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$subtract": [
"$date",
1000 * 60 * 60 * 24
]
}
}
},
{ /* else return actual date */
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$date"
}
}
]
},
"isNight": {
"$or": [
{ "$gte": [ { "$hour": "$date" }, 21 ] },
{ "$lt": [ { "$hour": "$date" }, 8 ] }
]
}
}
},
{ "$match": { "isNight": true } },
{
"$group": {
"_id": "$yearMonthDay",
"count": { "$sum": 1 }
}
}
])

更详细的方法涉及使用 $switch case 表达式代替 $cond 如下(感谢 @Styvane ):

db.sensors.aggregate([
{
"$addFields": {
"yearMonthDay": {
"$switch": {
"branches": [
{
"case": { "$lt": [ { "$hour": "$date" }, 8 ] },
"then": { /* subtract one day from a measurement at < 08:00 */
"$dateToString": {
"format": "%Y-%m-%d",
"date": {
"$subtract": [
"$date",
1000 * 60 * 60 * 24
]
}
}
}
},
{
"case": { "$gte": [ { "$hour": "$date" }, 8 ] },
"then": { /* return actual date */
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$date"
}
}
}
]
}
},
"isNight": {
"$or": [
{ "$gte": [ { "$hour": "$date" }, 21 ] },
{ "$lt": [ { "$hour": "$date" }, 8 ] }
]
}
}
},
{ "$match": { "isNight": true } },
{
"$group": {
"_id": "$yearMonthDay",
"count": { "$sum": 1 }
}
}
])

关于mongodb - 按日期对 MongoDB 数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41930686/

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