mongodb bson.errors.InvalidBSON:日期值超出范围

cbjzeqam  于 2023-10-16  发布在  Go
关注(0)|答案(2)|浏览(196)

我需要你的帮助我正在使用Python从mongoDb服务器获取数据。在获取数据时,我遇到错误。

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:日期值超出范围”

我到处都找遍了,但找不到解决办法。问题是我在**db.find({})**阶段得到了一个错误,所以我无法在管道的后面阶段处理这个错误。请问您能告诉我如何处理这个错误吗?
我试图解决这个错误,但没有解决。

62lalag4

62lalag41#

尝试像这样处理异常:

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}")
jk9hmnmh

jk9hmnmh2#

太奇怪了上面的代码尝试简单地返回具有特定列的文档,因此即使没有对日期列进行有效性检查,也应该可以工作。我在下面的集合上尝试了相同的代码,它确实工作:

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)

它返回以下内容:

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'}

相关问题