[Python] Pymongo query with dates returns no results

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I have the following python 3.12.4 code that inserts a JSON in a mongoDB deployed locally through a docker container using dockerhub' image "mongo:4.4.7"

    myClient = pymongo.MongoClient("mongodb://%s:%s@%s" % (MONGO_USER, MONGO_PASS, MONGO_CONN), timeoutMS=10000)
    myDB = myClient[CLIENT_NAME]
    myCollection = myDB[COLLECTION_NAME]

    the_json = '{"id": "json1","thedate": "2020-05-11T12:22:34.876Z"}'
    myRecord = json.loads(the_json)
    # replace str date with python' datetime object
    myRecord["thedate"] = datetime.strptime(myRecord["thedate"], "%Y-%m-%dT%H:%M:%S.%fZ")
    insertionResult = myCollection.insert_one(myRecord)

    startDate = datetime(2020, 8, 12, 4, 21, 3, 923453)
    mySearch = myCollection.find({"thedate": {"$gt": startDate}})


    The above code returns records correctly.

    The problem starts when using the very same python code against the very same dockerhub' image and the same python libraries in a kubernetes cluster. In such case, no records are returned. The curious part is that, in such cluster deployment, when I execute a "mySearch = myCollection.find()" it gets all the records in the DB, so there are no connectivity issues...

    I have tried several types of date types to perform the search such as:

    startDate = datetime(2012, 11, 2, 11, 10, 13, 123123, pytz.UTC)
    startDate = datetime.now(tz=pytz.utc)- timedelta(days=7)
    startDate = datetime(2013, 3, 12, 6, 54, 4, 123123)
    startDate = datetime.now() - timedelta(days=4)


    Just in case, the date of all containers:

    MY PC DATE: lun 21 oct 2024 18:27:08 CEST+0200
    DATE MONGODB RUN IN DOCKERS LOCALLY: Mon Oct 21 16:26:43 UTC 2024 +0000
    DATE MONGODB RUN IN KUBERNETES: Mon Oct 21 16:29:24 UTC 2024 +0000
    DATE PYTHON CODE KUBERNETES: Mon Oct 21 16:30:44 UTC 2024 +0000


    As you can see, the date is stored with ISOdate, which seems correct to me. When I perform the following check using Mongo CLI the data type of the date stored in the DB seems also fine:

    > date_obj = db["collection-name"].findOne({ thestr: 'exampleFile' }).thedate
    ISODate("2024-10-15T11:59:59.111Z")
    > date_obj.toString()
    Tue Oct 15 2024 11:59:59 GMT+0000 (UTC)


    Any clue about what could be happening? why is it working locally but not in kubernetes? Thanks in advance!!

    Continue reading...

Compartilhe esta Página