當然,這是不可能的,你想要的是功能SERVER-6036,它是未實現的。
對於這樣一個長期運行的任務,我建議對索引字段進行查詢。例如。如果你的文件都有一個時間戳「TS」:
documents = list(collection.find().sort('ts').limit(1000))
for doc in documents:
# ... process doc ...
while True:
ids = set(doc['_id'] for doc in documents)
cursor = collection.find({'ts': {'$gte': documents[-1]['ts']}})
documents = list(cursor.limit(1000).sort('ts'))
if not documents:
break # All done.
for doc in documents:
# Avoid overlaps
if doc['_id'] not in ids:
# ... process doc ...
此代碼遍歷光標完全,所以它不超時,然後處理1000個文檔,然後重複下一個1000
二理念:用a very long cursor timeout配置您的服務器:
mongod --setParameter cursorTimeoutMillis=21600000 # 6 hrs
第三個想法:你可以更多一些,雖然不是完全一定的,你會在一個使用它關閉不超時光標聲明:
cursor = collection.find(..., no_cursor_timeout=True)
with cursor:
# PyMongo will try to kill cursor on server
# if you leave this block.
for doc in cursor:
# do stuff....
是在可能的情況,但對我來說,我有一些非常複雜的查詢,我不想每次都用新的查詢,以重新啓動模式是有用的 - 我想保持一個遊標在服務器上以某種方式打開 – nonagon
我已更新我的答案。你問「如果有人知道是否有可能」,我已經明確地回答了。 =) –
你的答案確實完整,所以我接受它。我想我只是有一個堆棧溢出寵物peeve,因爲每次我問一個焦點問題「我該怎麼做X」我總是得到一百萬憤怒的答覆說:「你不想做X你應該做Y或Z」時當然Y或Z是不可能的在我的情況下,但它會解釋太多的上下文:)。無論如何謝謝你的答案,這確實是相當有幫助的! – nonagon