InvalidBSON消耗游标并引发StopIteration。如何跳过不好的文档?游标、跳过、消耗、不好

由网友(最完整的数字是十二)分享简介:我正在浏览一个集合,该集合的一个文档中包含一些错误的日期时间数据。mongo_query = {}mongo_projection = {"createdAt": True} # many more date columns ommitted heremongo_cursor = collection.find(m...

我正在浏览一个集合,该集合的一个文档中包含一些错误的日期时间数据。

mongo_query = {}
mongo_projection = {"createdAt": True} # many more date columns ommitted here
mongo_cursor = collection.find(mongo_query,
                               projection=mongo_projection
                               no_cursor_timeout=True)

迭代游标文档:

for i in range(100):
    try:
        mongo_cursor.next()
    except InvalidBSON:
        pass
发动机涡轮介入之后,什么时候停止运作

我希望迭代程序在处理InvalidBSON错误后继续,但在错误之后,.__next__()引发StopIteration错误,游标中没有更多文档。

我已尝试使用for doc in mongo_cursor()访问文档并将其转换为列表list(mongo_cursor()),但都以类似的方式失败。

在pymongo中有什么方法可以跳过游标中的错误数据吗?或者有没有更好的方法来处理这件事?

推荐答案

遇到无效BSON时,PYMOGO将停止迭代。理想情况下,您应该清理无效记录,而不是处理它;但您可能不知道哪些记录是无效的?

以下代码将作为权宜之计。不是获取完整记录,而是只获取_id,然后对记录执行find_one()操作;您可以将其放在try...except中以清除无效记录。

顺便说一句,您可以很容易地在pymongo中重现InvalidBSON错误(用于测试!!)使用Mongo外壳添加0001年之前的日期:

db.mycollection.insertOne({'createdAt': new Date(-10000000000000)}) // valid in pymongo
db.mycollection.insertOne({'createdAt': new Date(-100000000000000)}) // **Not** valid in pymongo
db.mycollection.insertOne({'createdAt': new Date(-100000000)}) // valid in pymongo

pymongo代码:

from pymongo import MongoClient
from pymongo.errors import InvalidBSON

db = MongoClient()['mydatabase']
collection = db['mycollection']

mongo_query = {}
mongo_date_projection = {"createdAt": True} # many more date columns ommitted here
mongo_projection = {"_id": 1} # many more date columns ommitted here
mongo_cursor = collection.find(mongo_query,
                               projection=mongo_projection,
                               no_cursor_timeout=True)

for record in mongo_cursor:
    record_id = record.get('_id')
    try:
        item = collection.find_one({'_id': record_id}, mongo_date_projection)
        print(item)
    except InvalidBSON:
        print(f'Record with id {record_id} contains invalid BSON')

给出类似以下内容的输出:

{'_id': ObjectId('5e6e1811c7c616e1ac58cbb3'), 'createdAt': datetime.datetime(1653, 2, 10, 6, 13, 20)}
Record with id 5e6e1818c7c616e1ac58cbb4 contains invalid BSON
{'_id': ObjectId('5e6e1a73c7c616e1ac58cbb5'), 'createdAt': datetime.datetime(1969, 12, 31, 23, 43, 20)}
阅读全文

相关推荐

最新文章