gpt4 book ai didi

python - MongoDB 聚合最近记录并将某些字段匹配到最近 30 天

转载 作者:太空宇宙 更新时间:2023-11-03 14:37:36 25 4
gpt4 key购买 nike

我试图获取每个 $src 的最后/最新值的返回值,但也在 #inches 字段上获取 30 天的 $min 和 $max。请参阅下面的查询

        date = datetime.datetime.today() - datetime.timedelta(days=31)

last_data = collection.aggregate([
{"$group": {"_id": "$src",
"date": {"$last": "$time"},
"inches": {"$last": "$inches"},
"low":{"$min":"$inches"},
"high":{"$max":"$inches"}
} }
])

这工作得很好,除了 LOW 和 HIGH 始终是永远的低和高。我想将最低价和最高价限制为仅在过去 30 天内拉动。如果可能,使用日期时间 timedelta 对象。

下面是返回特定日期的所有数据的示例。我不知道如何将两个查询合并为一个。

      data = collection.find({'time':{ "$gte" : (date) }})

更新 1:尝试以下代码...

注意:日期是 30 天前的纪元时间今天 = 1508360994.741111日期 = 1505682594.741111

collection.aggregate([
{"$group": {"_id": "$src",
"date": {"$last": "$time"},
"inches": {"$last": "$inches"},
"low": {
"$min": {
"$cond": [
{"time": {"$lte": ["$time", date]}},
"$inches",
None
]
}
},
"high": {
"$max": {
"$cond": [
{"time": {"$gte": ["$time", date]}},
"$inches",
None
]
}
},
}}
])

我得到这样的返回:看来它可能有效。我需要做一些健全性检查来确保。 {'_id': 'c4028504', '日期': datetime.datetime(2017, 10, 16, 2, 47, 21, 939000), '英寸': 85.0, '低': 0, '高': 2007.25} ,

如何添加第二个条件以仅显示 > 0 的低点。请参阅下面我的粗糙尝试。

                   "low": {
"$min": {
"$cond": [ { "$and" : [
{ "time": {"$gte": ["$time", date] },
{ "inches": {"$gt": ["$inches", 0] }
]},
"$inches",
None
]}
}
},

最佳答案

两者min & max当所有值不为空或缺失时,在比较中忽略空值和缺失值。

您可以使用上述想法来构建以下查询。

“today”是日期时间 utc 值,“date”是以毫秒为单位的增量。 (例如:30 * 86400 *1000 持续 30 天)。

本质上使用条件运算符,计算 $time 和“today”之间的差异并进行比较,如果差异小于输入值(以毫秒为单位),则 $inches else null.

"low": {
"$min": {
"$cond": [
{
"$lte": [
{
"$subtract": [
"$time",
today
]
},
date
]
},
"$inches",
null
]
}
}

您可以对 $max (高)应用类似的逻辑并调整 python 的答案。

关于python - MongoDB 聚合最近记录并将某些字段匹配到最近 30 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46815740/

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