How to query using ISODate in PyMongo?

339 Views Asked by At

Long story short, I'm trying to do this query in PyMongo for the last two days. Please help.

for x in restaurants.find( 
            {"grades":
             {"$elemMatch":
              {'date': dateutil.parser.parse("2014-08-11T00:00:00Z"),
               'grade':'A',
               'score':11
              }}},
{"name":1,
 "grades.grade":1,
 "grades.score":1,
 "grades.date":1
}):
print(x)

Edit: Here's the database. It's Structure: enter image description here

I'm trying to write a query to find the restaurant Id, name, and grades for those restaurants which achieved a grade of "A" and scored 11 on an ISODate "2014-08-11T00:00:00Z" among many of survey dates.

I'm starting to think there's something wrong with either the date I'm entering or the database. Also, as you can see in the fourth line of code I AM using a time object. Please try querying yourself. Its not working.

1

There are 1 best solutions below

4
Tom Slabbaert On

pymongo doesn't use "ISODate", it's a Mongo type, you should just use datetime to create a time object, like so:

from datetime import datetime
import pytz

parsed_date = datetime.strptime("2014-08-11T00:00:00Z", '%Y-%m-%dT%H:%M:%SZ')
timezone = pytz.timezone("UTC")
with_timezone = timezone.localize(parsed_date)

for x in restaurants.find(
        {
            "grades":
                {
                    "$elemMatch": {
                        'date': with_timezone,
                        'grade': 'A',
                        'score': 11
                    }
                }
        },
        {
            "name": 1,
            "grades.grade": 1,
            "grades.score": 1,
            "grades.date": 1
        }):
    print(x)