[英]How I can find closest date by single request using pymongo? Date should be closest to Current Date
数据集:
{"_id":{"$oid":"61e038a052124accf41cb5e4"},"event_date":{"$date":{"$numberLong":"1642204800000"}},
"name":"UFC Fight Night","event_url":"https://www.tapology.com/fightcenter/events/82805-ufc-fight-night","location":"Las Vegas, NV"}
{"_id":{"$oid":"61e038a252124accf41cb5e5"},"event_date":{"$date":{"$numberLong":"1642809600000"}},"name":"UFC 270","event_url":"https://www.tapology.com/fightcenter/events/82993-ufc-270","location":"Anaheim, CA"}
{"_id":{"$oid":"61e038a252124accf41cb5e6"},"event_date":{"$date":{"$numberLong":"1644019200000"}},"name":"UFC Fight Night","event_url":"https://www.tapology.com/fightcenter/events/83125-ufc-fight-night","location":"Las Vegas, NV"}
我正在使用 python,这意味着我无法在 Mongo DB 的代码中使用 $commands 来查找我需要的集合。 问题是如何找到 object 应该具有最接近当前日期的日期时间值。 据我了解,我必须使用 python 的 datetime.now() 来设置当前日期并进行比较($currentDate 不适用于 Python)。 但是为了比较值,我必须反序列化 object,这看起来很重。 默认情况下,Mongo 使用 ISO 日期时间类型。
你能帮助我吗? 至少有方向让我走上正确的道路?
这是一个聚合的解决方案
db.collection.aggregate([
{
"$addFields": {
"dateDiff": {
"$abs": {
"$subtract": [
"$event_date",
{
"$literal": new Date()
}
]
}
}
}
},
{
"$sort": {
"dateDiff": 1
}
}
])
$subtract
来区分event_date
和今天。$abs
是要有绝对值。 在未来或过去拥有最近的。dateDiff
排序在您的代码中,您必须替换new Date()
在这里试试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.