StormsEdge
StormsEdge

Reputation: 885

Pymongo Query for Date is failing

I have a query that works fine in mongodb compass, but the moment I bring it over into Jupyter it breaks. The issue is something to do with the date filter.

I have tried both:

cursor = prod_db.my_collection.find({"date": {"$eq": "new Date('2021-04-26')"}, "type": "Regular"})

as well as

cursor = prod_db.my_collection.find({"date": "new Date('2021-04-26')", "type": "Regular"})

If I remove the date query, I get a return that I would expect, which validates that the db connection is set up properly and that the "type" filter is valid. What am I missing here?

Upvotes: 0

Views: 533

Answers (2)

Vivek
Vivek

Reputation: 161

Issues mapping date columns across python and Mongo happens primarily because Mongo stores the date as a JavaScript date object and then wraps the ISODate format around it. However if the date values that we are trying to pass from python onto mongo is in datetime format ( like @hhharsha36 mentioned above) one should be good

I found this article helpful when I was going through some hellish time using dates from pandas and python variables and using that to query/insert/update in Mongo : (https://medium.com/nerd-for-tech/how-to-prepare-a-python-date-object-to-be-inserted-into-mongodb-and-run-queries-by-dates-and-range-bc0da03ea0b2)

Upvotes: 0

hhharsha36
hhharsha36

Reputation: 3349

new Date is the date keyword for MongoShell. You should replace it with python's built-in datetime package.

from datetime import datetime
cursor = prod_db.my_collection.find({"date": datetime(2021, 4, 26), "type": "Regular"})

Upvotes: 1

Related Questions