Search code examples
pythonmongodbpymongopython-datetime

How to fetch documents based on from and to date using pymongo?


I have a large mongodb collection that have "date" field as :

'date': '2020-06-11 10:05:03.718804'

I would like to find documents between from and to date.

Data in Mongo: (Sample Collection)

{
"_id":"001",
"color":"Blue",
"status":"available",
"date": "2020-06-11 10:05:03.718804"
},
{
"_id":"002",
"color":"Gold",
"status":"available",
"date": "2020-06-12 11:25:03.714804"
},
{
"_id":"003",
"color":"Violet",
"status":"available",
"date": "2020-06-13 11:25:03.714804"
},
{
"_id":"004",
"color":"White",
"status":"available",
"date": "2020-06-14 11:44:23.618704"
}

Pymongo

from datetime import datetime
from_date = "2020-06-11 10:05:03.718804"
to_date = "2020-06-13 11:44:23.618704"
details = db.collection.find({date: {$gt: from_date, $lt:to_date}})
print(details)

Output: Should list the data between from and to dates.

Error facing: Invalid token, $gt and $lt is invalid.

How to find the documents based on date condition?

Thanks in advance.


Solution

  • You can use ISODate to convert strings to comparable dates.

    from_date = "2020-06-11 10:05:03.718804"
    to_date = "2020-06-13 11:44:23.618704"
    details = db.collection.find({"date": { $gte: ISODate(from_date), $lt: ISODate(to_date)}})
    print(details)