cursor.noCursorTimeout()
Nesta página
Definição
cursor.noCursorTimeout()
Importante
Método mongosh
Esta página documenta um método
mongosh
. Esta não é a documentação para um driver específico de idioma, como Node.js.Para drivers de API do MongoDB, consulte a documentação do driver do MongoDB específica da linguagem.
Instructs the server to avoid closing a cursor automatically after a period of inactivity.
O método
noCursorTimeout()
tem a seguinte forma de protótipo:db.collection.find(<query>).noCursorTimeout()
Compatibilidade
Esse método está disponível em implantações hospedadas nos seguintes ambientes:
MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem
Importante
Esse comando não é suportado em clusters M0, M2, M5 e Flex. Para obter mais informações, consulte Comandos não suportados.
MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB
MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB
Comportamento
O tempo limite de inatividade da sessão substitui noCursorTimeout
Os drivers MongoDB e mongosh
associam todas as operações a uma sessão do servidor, com exceção das operações de gravação não reconhecidas. No caso das operações não associadas explicitamente a uma sessão (ou seja, usando Mongo.startSession()
), os drivers MongoDB e mongosh
criam uma sessão implícita e a associam à operação.
If a session is idle for longer than 30 minutes, the MongoDB server
marks that session as expired and may close it at any time. When the
MongoDB server closes the session, it also kills any in-progress
operations and open cursors associated with the session. This
includes cursors configured with noCursorTimeout()
or
a maxTimeMS()
greater than 30 minutes.
Consider an application that issues a db.collection.find()
with cursor.noCursorTimeout()
. The server returns a cursor along
with a batch of documents defined by the cursor.batchSize()
of
the find()
. The session refreshes each time the
application requests a new batch of documents from the server. However,
if the application takes longer than 30 minutes to process the current
batch of documents, the session is marked as expired and closed. When
the server closes the session, it also kills the cursor despite the
cursor being configured with noCursorTimeout()
. When the
application requests the next batch of documents, the server returns an
error.
Refresh a Cursor with refreshSessions
Para operações que retornam um cursor, se o cursor ficar inativo por mais de 30 minutos, execute a operação em uma sessão explícita usando e atualize periodicamente Mongo.startSession()
refreshSessions
a sessão usando o comando. Por exemplo:
var session = db.getMongo().startSession() var sessionId = session sessionId // show the sessionId var cursor = session.getDatabase("examples").getCollection("data").find().noCursorTimeout() var refreshTimestamp = new Date() // take note of time at operation start while (cursor.hasNext()) { // Check if more than 5 minutes have passed since the last refresh if ( (new Date()-refreshTimestamp)/1000 > 300 ) { print("refreshing session") db.adminCommand({"refreshSessions" : [sessionId]}) refreshTimestamp = new Date() } // process cursor normally }
In the example operation, the db.collection.find()
method is
associated with an explicit session. The cursor is configured with
cursor.noCursorTimeout()
to prevent the server from closing
the cursor if idle. The while
loop includes a block that uses
refreshSessions
to refresh the session every 5 minutes.
Since the session will never exceed the 30 minute idle timeout, the
cursor can remain open indefinitely.
Para drivers MongoDB, consulte a documentação do driver para obter instruções e sintaxe para criar sessões.