簡體   English   中英

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

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

當我嘗試根據創建日期返回文檔時,當我知道數據庫中有符合條件的文檔時,我會得到一個空列表。 我使用 postman 發送請求,該請求將是用戶輸入的字符串,例如。 "Tue Apr 28 2020" 然后,此字符串輸入將被轉換為日期時間 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)

這是部分數據庫 model:

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

創建文檔時,它存儲在數據庫中,時間存儲為isoformat() 用戶只能使用日期選擇器以上述格式輸入搜索字段,因此我將日期格式化為適合 Mongodb 可以理解的格式。

使用上面的代碼,我得到一個空列表和 200 狀態代碼。 檢查數據庫顯示我有符合標准的文件,任何人都可以幫助找出問題所在嗎? 謝謝。

如果您可以將 search_field 和 nextday 設置為日期時間格式,那么您可以編寫查詢。 我還建議在 mongoengine 中使用Q進行 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM