最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

【已解决】Python的pymongo中根据指定字段的时间范围去查询数据且排序

Python crifan 291浏览 0评论

折腾:

【记录】Flask项目中新增获取用户历史评测报告

期间,需要对于:

去用Python的pymongo查询出来:

user_id:为某个用户的id,比如28

start_time:满足当前时间之前最近半年范围内的

且最好能对于结果去排序

pymongo find datetime compare

python – MongoDB / Pymongo Query with Datetime – Stack Overflow

好像直接用:

for doc in db.wing_model.find({'time': {'$gte': start, '$lt': end}}):

就可以了?

MongoDB Query by DateTime with Python – Stack Overflow

db.collection.find({"datefield" : ISODate("YYYY-MM-DDTHH:MM:SS")})
db.collection.find({"datefield" : {"$gte" : <beginning_of_day_as_ISODate>, "$lte" : <end_of_day_as_ISODate>})
{createdDate : {$gte : ISODate("2017-12-06T00:00:00"), $lte : ISODate("2017-12-06T23:59:59")}}

Date() — MongoDB Manual

python – pymongo query by datetime – Stack Overflow

python – Query DateTime with PyMongo – Stack Overflow

db.collection.find({'createTime':{'$lt':datetime.datetime.now(), '$gt':datetime.datetime.now() - timedelta(hours=24)}})

去试试

curTime = datetime.datetime.now()
halfYearBeforeTime = curTime - datetime.timedelta(days = settings.USER_EVAL_REPORT_DAYS_AGO)
userEvaluations = evalCollection.find({
    "user_id": userId,
    "start_time": {
        "$gte": halfYearBeforeTime,
        "$lte": curTime
    }
})
log.debug("userEvaluations=%s", userEvaluations)
for eachEvaluation in userEvaluations:
    log.debug("eachEvaluation=%s", eachEvaluation)

是可以搜到的:

log输出是有内容的:

然后再去排序

pymongo find sort by time

python – pymongo sorting by date – Stack Overflow

去试试

通过:

timeKeyName = "start_time"
# timeKeyName = "finish_time"
halfYearBeforeTime = curTime - datetime.timedelta(days = settings.USER_EVAL_REPORT_DAYS_AGO)
userEvaluations = evalCollection.find({
    "user_id": userId,
    timeKeyName: {
        "$gte": halfYearBeforeTime,
        "$lte": curTime
    }
}).sort(timeKeyName, pymongo.ASCENDING)

是可以的排序的。

另外还需要去:

想要把返回值变成list

pymongo find cursor to list

How to make pymongo’s find() return a list? – Stack Overflow

myresults = list(mydb.mycollection.find())

直接用list即可:

curTime = datetime.datetime.now()
# timeKeyName = "start_time"
timeKeyName = "finish_time"
earliestTime = curTime - datetime.timedelta(days = settings.USER_EVAL_REPORT_DAYS_AGO)
userEvaluations = evalCollection.find({
    "user_id": userId,
    timeKeyName: {
        "$gte": earliestTime,
        "$lte": curTime
    }
}).sort(timeKeyName, pymongo.DESCENDING).limit(settings.USER_EVAL_REPORT_LIMIT_NUM)

userEvaluationList = list(userEvaluations)

【总结】

最后用:

import pymongo
import datetime

curTime = datetime.datetime.now()
# timeKeyName = "start_time"
timeKeyName = "finish_time"
earliestTime = curTime - datetime.timedelta(days = 30*6)
userEvaluations = evalCollection.find({
    "user_id": userId,
    timeKeyName: {
        "$gte": earliestTime,
        "$lte": curTime
    }
}).sort(timeKeyName, pymongo.DESCENDING).limit(20)
userEvaluationList = list(userEvaluations)
userEvaluationList.reverse()
historyList = []
for eachEvaluation in userEvaluationList:
    if "overall_level" in eachEvaluation:
        curTimeLevelDict = {
            "time": eachEvaluation[timeKeyName],
            "overall_level": eachEvaluation["overall_level"]
        }
        historyList.append(curTimeLevelDict)
log.debug("historyList=%s", historyList)

实现了想要的逻辑:

  • 去mongodb查询

  • 最早半年前,最晚当前时间

  • 结果中再去根据时间倒序

  • 然后再去取最多20个

  • 从而实现:最近半年,最多20个,只不过顺序是反的而已

  • 对于时间倒序后的结果,再调换顺序

  • 即可得到我要的:

    最近半年的,最多20个,按照时间升序排列

    然后输出希望的结果:

    转载请注明:在路上 » 【已解决】Python的pymongo中根据指定字段的时间范围去查询数据且排序

    发表我的评论
    取消评论

    表情

    Hi,您需要填写昵称和邮箱!

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址
    61 queries in 0.118 seconds, using 18.86MB memory