1

I've got a very small script that's trying to find some docs in mongodb where a certain field has today's date.

To me, as a noob, it looks like I have a good connection - but I get no results.

Wondering if it has something to do with my date formatting?

Here's my script:

import pymongo
from datetime import date

thedate = date.today().isoformat()

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["hotels"]
collection = db["grand_native_test"]

query = {"skaptdato": {"$gt": thedate} }

doit = collection.find(query)

print(query)
print(collection)

for x in doit:
    print(x)

And the result is simply:

{'skaptdato': {'$gt': '2019-05-30'}}
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'hotels'), u'grand_native_test')

I've spent like 4 hours on this, really basic, script - but I can't for the life of me figure it out.

BTW: Running mongodb 3.6.3, the latest pymongo-release and python 2.7.15.

BTW-2: The formatting of the db-fields also includes minutes and seconds --> 2019-05-30 13:54:00.645Z ...

I sure hope one of you smart folks have a hint for a poor noob.

1 Answer 1

1

I assume the problem is in data types. For example, the DB's field contains ISODate type and compare with string type. Use the next code for MongoDB:

{skaptdato: {'$gt': ISODate('2019-05-30')}}

Use the next code for pymongo:

from datetime import datetime
...
your_date_string = '2019-05-30'
date_string_to_date = datetime.strptime(your_date_string, '%Y-%m-%d')
...
{'skaptdato': {'$gt': date_string_to_date}}
Sign up to request clarification or add additional context in comments.

2 Comments

Sounds sensible. But this only throws this error: NameError: name 'ISODate' is not defined
O, it's my fault. ISODate for mongoDD, datetime for python

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.