エラー内容
MongDBで、検索した結果(約4万件)をforループ内でひとつづつ処理していく最中に、以下のようなエラーが発生しました。
Exception has occurred: CursorNotFound
cursor id 1180948255076503304 not found, full error: ....
また、実行していたPythonのコードは、次のようなものです。MongoDBのドライバはpymongoを使用しています。
with MongoClient(driver_URL) as client:
webcamDb = client.webcam
collection = webcamDb.webcam
# search all information
for webCamInfo in collection.find():
#何らか処理
対応内容
調べたところ、上記エラーは、既に閉じられたか、タイムアウトしたカーソルを使用しようとした時に発生するエラーとのこと。対策としては、
- データを一度に少量ずつ処理する(バッチ処理)
- サーバー側でカーソルのタイムアウト時間を延長する
- エラーハンドリングとリトライのロジックを実装する
等、いくつかありましたが、2のタイムアウト時間の調整は、適切な値がよくわからないこと、3のリトライはエラーの発生が前提のため気が進まなかったため、バッチ処理で1000件づつ処理するようにしました。
with MongoClient(driver_URL) as client:
webcamDb = client.webcam
collection = webcamDb.webcam
last_id = None
query = {}
batch_size = 1000
while True:
if last_id:
query['_id'] = {'$gt': last_id}
webCamlist = list(webCamCol.find(query).sort('_id', ASCENDING).limit(batch_size))
if not webCamlist:
break
process_batch(webCamlist) #何らかの処理
last_id = webCamlist[-1]['_id']