如何使用flask-mongoengine的$gte和$lte在MongoDB中查询日期?

问题描述 投票:0回答:1

当我试图根据创建的日期返回文档时,当我知道数据库中有符合标准的文档时,我得到的是一个空列表。我使用postman来发送请求,这将是一个来自用户的字符串输入,例如。"Tue Apr 28 2020". 这个字符串输入将被转换为一个日期时间对象,就像这样。

def get(self):
        try:
            body = request.get_json()
            search_field = datetime.datetime.strptime(body, '%a %b %d %Y') #format string to datetime object

            next_day = search_field
            next_day += relativedelta(days=1) #Set the end of the range to the next day

            search_field = search_field.replace(tzinfo=datetime.timezone.utc).isoformat()
            next_day = next_day.replace(tzinfo=datetime.timezone.utc).isoformat()
            print(search_field) #Verify the fields are correct : 2020-04-28T00:00:00+00:00
            print(next_day) #2020-04-29T00:00:00+00:00

            date_search = Reports.objects.filter(__raw__={'creation_timestamp' : {'$gte' : search_field, '$lte' : next_day}}).to_json() #This is where the documents should be filtered for return
            print(date_search)

            return Response(date_search, mimetype="application/json", status=200) #The document/s should be returned here as a JSON array.

        except Exception as e:
            print(e)
            return make_response(jsonify(message='Something went wrong :('), 401)

这里是部分数据库模型。

class Reports(db.Document):    
    creation_timestamp = db.DateTimeField(default=datetime.utcnow, required=True)

当文档被创建时,它被存储在数据库中,时间被存储为 isoformat(). 用户只能用日期选取器按上面说的格式输入搜索字段,所以我把日期的格式调整为符合Mongodb能理解的格式。

使用上面的代码,我得到一个空列表和200状态码。检查数据库显示我有符合标准的文档,谁能帮我找出问题所在?谢谢。

python mongodb flask pymongo mongoengine
1个回答
3
投票

如果你能让你的search_field和nextday是datetime格式,那么你就可以写查询。我也建议使用 Q 在mongoengine中进行pymongo查询,你的查询。

import Q from mongoengine
search_time=datetime.datetime(2017, 11, 8)
nextday=datetime.datetime(2017, 11, 9)
date_search=Report.objects(Q(creation_timestamp__gte=search_field) & Q(timestamp__lte=nextday)).to_json()
© www.soinside.com 2019 - 2024. All rights reserved.