首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用$gte和$lte结合flask-mongoengine查询MongoDB的日期?

如何使用$gte和$lte结合flask-mongoengine查询MongoDB的日期?
EN

Stack Overflow用户
提问于 2020-05-04 22:23:40
回答 1查看 517关注 0票数 0

当我尝试根据创建日期返回文档时,当我知道数据库中存在符合条件的文档时,会得到一个空列表。我使用postman发送请求,该请求将是用户输入的字符串,例如。"Tue Apr 28 2020"。然后,此字符串输入将被转换为datetime对象,如下所示:

代码语言:javascript
复制
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)

下面是部分数据库模型:

代码语言:javascript
复制
class Reports(db.Document):    
    creation_timestamp = db.DateTimeField(default=datetime.utcnow, required=True)

当文档被创建时,它被存储在数据库中,时间被存储为isoformat()。用户只能使用日期选择器以上述格式输入搜索字段,因此我将日期格式设置为适合Mongodb可以理解的格式。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-05 05:58:15

如果可以将search_field和nextday设置为datetime格式,则可以编写查询。我还建议在mongoengine中使用Q进行pymongo查询。您的查询:

代码语言:javascript
复制
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()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61594497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档