skip to Main Content

I need your help. I am fetching data from a mongoDb server using Python. While fetching data I encounter an error.

 drivers = mongodb_global('drivers')
    filter_col = {
        "created": 1,
        "updated": 1,
        "_id": 1,
        "name": 1,
        "birthday": 1,
        "id_expiry": 1,
        "license_expiry": 1
    }

    data = drivers.find({}, filter_col)
    driver_lst = []
    for item in data:
        print(item)

"return EPOCH_NAIVE + datetime.timedelta(seconds=seconds,
bson.errors.InvalidBSON: date value out of range"

I have searched everywhere but couldn’t find a solution. the problem is that I am getting an error at the db.find({}) stage, so I am unable to handle this error in the later stages of the pipeline. Could you please guide me, how to handle this error?

I have tried to solve this error but not solved.

2

Answers


  1. Try to handle the exception like:

    import pymongo
    from pymongo.errors import InvalidBSON
    
    drivers = mongodb_global('drivers')
    filter_col = {
        "created": 1,
        "updated": 1,
        "_id": 1,
        "name": 1,
        "birthday": 1,
        "id_expiry": 1,
        "license_expiry": 1
    }
    
    data = drivers.find({}, filter_col)
    driver_lst = []
    
    for item in data:
        try:
            print(item)
        except InvalidBSON as e:
            print(f"Invalid document: {e}")
    
    Login or Signup to reply.
  2. This is so strange.
    Your code above try to simply return documents with specific columns, so that should work even if there is no validity check of the date column. I have tried the same code on the following collection and it does work :

    import pymongo      
    client = pymongo.MongoClient("mongodb://xxx:xxxx@localhost:27017/?authMechanism=DEFAULT"
    filter_col = {
        "address": 1,
        "date": 1,
        "_id": 1,
    }
    
    db = client["test"]  
    collection = db["customers"]
    
    data = collection.find({}, filter_col)
    
    for item in data:
        print(item)
    

    It returns this:

    python .script.py
    {'_id': ObjectId('652bef9a87af75d75bc425ca'), 'address': 'Apple st 652', 'date': None}
    {'_id': ObjectId('652bef9a87af75d75bc425cb'), 'address': 'Mountain 21', 'date': datetime.datetime(2018, 4, 15, 16, 54, 40)}
    {'_id': ObjectId('652bef9a87af75d75bc425cc'), 'address': 'Valley 345'}
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search