简体   繁体   English

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

[英]How to query dates in MongoDB using $gte and $lte with flask-mongoengine?

When I try to return documents based on the date created, I get an empty list when I know for a fact that there are documents in the database that meet the criteria.当我尝试根据创建日期返回文档时,当我知道数据库中有符合条件的文档时,我会得到一个空列表。 I used postman to send the request which would be a string input from the user eg.我使用 postman 发送请求,该请求将是用户输入的字符串,例如。 "Tue Apr 28 2020" . "Tue Apr 28 2020" This string input would then be converted to a datetime object like so:然后,此字符串输入将被转换为日期时间 object,如下所示:

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)

Here is the partial database model:这是部分数据库 model:

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

When the document is created, it is stored in the database and the time is stored as isoformat() .创建文档时,它存储在数据库中,时间存储为isoformat() The user can only input the search field in the format stated above with a date picker so I format the date to fit the format Mongodb would understand.用户只能使用日期选择器以上述格式输入搜索字段,因此我将日期格式化为适合 Mongodb 可以理解的格式。

Using the above code, I get an empty list and the 200 status code.使用上面的代码,我得到一个空列表和 200 状态代码。 Checking the database shows I have documents that would fit the criteria, can anyone help figure out what is wrong?检查数据库显示我有符合标准的文件,任何人都可以帮助找出问题所在吗? Thanks.谢谢。

If you can have your search_field and nextday in datetime format then you can write the query.如果您可以将 search_field 和 nextday 设置为日期时间格式,那么您可以编写查询。 I also suggest using Q for pymongo queries in mongoengine.我还建议在 mongoengine 中使用Q进行 pymongo 查询。 Your query:您的查询:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM