Definição
db.currentOp()Importante
O comando de banco de dados do
currentOpé preterido desde a versão 6.2. Use o estágio de agregação$currentOpem vez do comandocurrentOpe seu método assistentemongoshdb.currentOp().Returns a document that contains information on in-progress operations for the database instance. The
db.currentOp()method wraps the database commandcurrentOp.Observação
A partir do MongoDB,5.0 o
$currentOpestágio de agregação é usado ao executar o método assistentedb.currentOp()mongoshcom.Diante disso, na 5.0 versão do shell e com mongosh, os conjuntos de resultados
db.currentOp()não estão sujeitos ao limite do tamanho de retorno de documento 16BSON de MB para documentos dasmongoversões anteriores do legado .
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 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
Sintaxe
db.currentOp() tem o seguinte formato:
db.currentOp(<operations>)
db.currentOp() can take the following optional argument:
Parâmetro | Tipo | Descrição |
|---|---|---|
booleano ou documento | Opcional. Especifica as operações a serem relatadas. Pode passar por um booleano ou um documento:
|
Comportamento
db.currentOp() pode aceitar um documento de filtro ou um parâmetro booleano.
If you pass a filter document to db.currentOp(), the output returns information only for the current operations that match the filter. The filter document can contain:
Campo | Descrição |
|---|---|
| Booleano. Se definido para Em instâncias do |
| Booleano. Se definido para If the document includes |
<filter> | Especifique as condições de filtro nos Campos de Saída. Veja exemplos. If the document includes |
Passing in true to db.currentOp() is equivalent to passing in a document of { "$all": true }. The following operations are equivalent:
db.currentOp(true) db.currentOp( { "$all": true } )
db.currentOp() and the database profiler report the same basic diagnostic information for all CRUD operations, including the following:
getMore(OP_GET_MORE ecommand)
Essas operações também são incluídas no logging de queries lentas. Consulte slowOpThresholdMs para obter mais informações sobre registro de queries lentas.
Controle de acesso
Em sistemas executados com authorization, o usuário deve ter acesso que inclua a ação de privilégio inprog.
Os usuários podem executar db.currentOp( { "$ownOps": true } ) em instâncias mongod para visualizar suas próprias operações mesmo sem a ação de privilégio inprog.
Exemplos
The following examples use the db.currentOp() method with various query documents to filter the output.
Operações de gravação aguardando um bloqueio
O exemplo a seguir retorna informações sobre todas as operações de gravação que estão aguardando um bloqueio:
db.currentOp( { "waitingForLock" : true, $or: [ { "op" : { "$in" : [ "insert", "update", "remove" ] } }, { "command.findandmodify": { $exists: true } } ] } )
Operações ativas sem rendimento
O exemplo a seguir retorna informações sobre todas as operações em execução ativas que nunca produziram:
db.currentOp( { "active" : true, "numYields" : 0, "waitingForLock" : false } )
Operações ativas em um banco de dados específico
O exemplo a seguir retorna informações sobre todas as operações ativas do banco de dados db1 que estão em execução há mais de 3 segundos:
db.currentOp( { "active" : true, "secs_running" : { "$gt" : 3 }, "ns" : /^db1\./ } )
Operações de indexação ativas
O exemplo a seguir retorna informações sobre operações de criação de índice em qualquer número de campos:
db.getSiblingDB("admin").aggregate( [ { $currentOp : { idleConnections: true } }, { $match: { $or: [ { "op": "command", "command.createIndexes": { $exists: true } }, { "op": "none", "msg": /^Index Build/ } ] } } ] )
Observação
Active Indexing Operations do not apply to rolling index builds.
Exemplo de saída
The following is a prototype of db.currentOp() output.
O seguinte é um protótipo do resultado currentOp ao executar em um standalone:
{ "inprog": [ { "type" : <string>, "host" : <string>, "desc" : <string>, "connectionId" : <number>, "client" : <string>, "appName" : <string>, "clientMetadata" : <document>, "active" : <boolean>, "currentOpTime" : <string>, "effectiveUsers" : [ { "user" : <string>, "db" : <string> } ], "opid" : <number>, "lsid" : { "id" : <UUID>, "uid" : <BinData> }, "secs_running" : <Long()>, "microsecs_running" : <number>, "op" : <string>, "ns" : <string>, "command" : <document>, "queryFramework" : <string>, "planSummary": <string>, "cursor" : { // only for getMore operations "cursorId" : <Long()>, "createdDate" : <ISODate()>, "lastAccessDate" : <ISODate()>, "nDocsReturned" : <Long()>, "nBatchesReturned" : <Long()>, "noCursorTimeout" : <boolean>, "tailable" : <boolean>, "awaitData" : <boolean>, "originatingCommand" : <document>, "planSummary" : <string>, "operationUsingCursorId" : <Long()> }, "msg": <string>, "progress" : { "done" : <number>, "total" : <number> }, "killPending" : <boolean>, "numYields" : <number>, "dataThroughputLastSecond" : <number>, "dataThroughputAverage" : <number>, "locks" : { "ParallelBatchWriterMode" : <string>, "ReplicationStateTransition" : <string>, "Global" : <string>, "Database" : <string>, "Collection" : <string>, "Metadata" : <string>, "oplog" : <string> }, "waitingForLock" : <boolean>, "lockStats" : { "ParallelBatchWriterMode" : { "acquireCount": { "r": <NumberLong>, "w": <NumberLong>, "R": <NumberLong>, "W": <NumberLong> }, "acquireWaitCount": { "r": <NumberLong>, "w": <NumberLong>, "R": <NumberLong>, "W": <NumberLong> }, "timeAcquiringMicros" : { "r" : Long(0), "w" : Long(0), "R" : Long(0), "W" : Long(0) }, "deadlockCount" : { "r" : Long(0), "w" : Long(0), "R" : Long(0), "W" : Long(0) } }, "ReplicationStateTransition" : { ... }, "Global": { ... }, "Database" : { ... }, ... } }, ... ], "fsyncLock": <boolean>, "info": <string>, "ok": <num> }
Veja a seguir um protótipo da saída currentOp quando executada no primário de um conjunto de réplicas:
{ "inprog": [ { "type" : <string>, "host" : <string>, "desc" : <string>, "connectionId" : <number>, "client" : <string>, "appName" : <string>, "clientMetadata" : <document>, "lsid" : { "id" : <UUID>, "uid" : <BinData> }, "transaction" : { "parameters" : { "txnNumber" : <Long()>, "autocommit" : <boolean>, "readConcern" : { "level" : <string> } }, "readTimestamp" : <Timestamp>, "startWallClockTime" : <string>, "timeOpenMicros" : <Long()>, "timeActiveMicros" : <Long()>, "timeInactiveMicros" : <Long()>, "expiryTime" : <string>, }, "active" : <boolean>, "currentOpTime" : <string>, "effectiveUsers" : [ { "user" : <string>, "db" : <string> } ], "opid" : <number>, "secs_running" : <Long()>, "microsecs_running" : <number>, "op" : <string>, "ns" : <string>, "command" : <document>, "originatingCommand" : <document>, "queryFramework" : <string>, "planSummary": <string>, "prepareReadConflicts" : <Long()>, "writeConflicts" : <Long()>, "cursor" : { // only for getMore operations "cursorId" : <Long()>, "createdDate" : <ISODate()>, "lastAccessDate" : <ISODate()>, "nDocsReturned" : <Long()>, "nBatchesReturned" : <Long()>, "noCursorTimeout" : <boolean>, "tailable" : <boolean>, "awaitData" : <boolean>, "originatingCommand" : <document>, "planSummary" : <string>, "operationUsingCursorId" : <Long()> }, "msg": <string>, "progress" : { "done" : <number>, "total" : <number> }, "killPending" : <boolean>, "numYields" : <number>, "dataThroughputLastSecond" : <number>, "dataThroughputAverage" : <number>, "locks" : { "ParallelBatchWriterMode" : <string>, "ReplicationStateTransition" : <string>, "Global" : <string>, "Database" : <string>, "Collection" : <string>, "Metadata" : <string>, "oplog" : <string> }, "waitingForLock" : <boolean>, "lockStats" : { "ParallelBatchWriterMode" : { "acquireCount": { "r": <NumberLong>, "w": <NumberLong>, "R": <NumberLong>, "W": <NumberLong> }, "acquireWaitCount": { "r": <NumberLong>, "w": <NumberLong>, "R": <NumberLong>, "W": <NumberLong> }, "timeAcquiringMicros" : { "r" : Long(0), "w" : Long(0), "R" : Long(0), "W" : Long(0) }, "deadlockCount" : { "r" : Long(0), "w" : Long(0), "R" : Long(0), "W" : Long(0) } }, "ReplicationStateTransition" : { ... }, "Global" : { ... }, "Database" : { ... }, ... } }, ... ], "fsyncLock": <boolean>, "info": <string>, "ok": <num>, "operationTime": <timestamp>, "$clusterTime": <document> }
A seguir está um exemplo da saída de currentOp quando executado em um mongos de um cluster fragmentado (os campos podem variar dependendo da operação que está sendo comunicada):
{ "inprog": [ { "shard": <string>, "type" : <string>, "host" : <string>, "desc" : <string>, "connectionId" : <number>, "client_s" : <string>, "appName" : <string>, "clientMetadata" : <document>, "lsid" : { "id" : <UUID>, "uid" : <BinData> }, "transaction" : { "parameters" : { "txnNumber" : <Long()>, "autocommit" : <boolean>, "readConcern" : { "level" : <string> } }, "readTimestamp" : <Timestamp>, "startWallClockTime" : <string>, "timeOpenMicros" : <Long()>, "timeActiveMicros" : <Long()>, "timeInactiveMicros" : <Long()>, "expiryTime" : <string>, }, "active" : <boolean>, "currentOpTime" : <string>, "effectiveUsers" : [ { "user" : <string>, "db" : <string> } ], "runBy" : [ { "user" : <string>, "db" : <string> } ], "twoPhaseCommitCoordinator" : { "lsid" : { "id" : <UUID>, "uid" : <BinData> }, "txnNumber" : <NumberLong>, "numParticipants" : <NumberLong>, "state" : <string>, "commitStartTime" : <ISODate>, "hasRecoveredFromFailover" : <boolean>, "stepDurations" : <document>, "decision" : <document>, "deadline" : <ISODate> } "opid" : <string>, "secs_running" : <Long()>, "microsecs_running" : <number>, "op" : <string>, "ns" : <string>, "command" : <document>, "configTime" : <Timestamp>, // Starting in 5.0 "topologyTime" : <Timestamp>, // Starting in 5.0 "queryFramework" : <string>, // Starting in 6.2 "planSummary": <string>, "prepareReadConflicts" : <Long()>, "writeConflicts" : <Long()>, "cursor" : { // only for getMore operations "cursorId" : <Long()>, "createdDate" : <ISODate()>, "lastAccessDate" : <ISODate()>, "nDocsReturned" : <Long()>, "nBatchesReturned" : <Long()>, "noCursorTimeout" : <boolean>, "tailable" : <boolean>, "awaitData" : <boolean>, "originatingCommand" : <document>, "planSummary" : <string>, "operationUsingCursorId" : <Long()> }, "msg": <string>, "progress" : { "done" : <number>, "total" : <number> }, "killPending" : <boolean>, "numYields" : <number>, "dataThroughputLastSecond" : <number>, "dataThroughputAverage" : <number>, "locks" : { "ParallelBatchWriterMode" : <string>, "ReplicationStateTransition" : <string>, "Global" : <string>, "Database" : <string>, "Collection" : <string>, "Metadata" : <string>, "DDLDatabase" : <string>, "DDLCollection" : <string>, "oplog" : <string> }, "waitingForLock" : <boolean>, "lockStats" : { "ParallelBatchWriterMode": { "acquireCount": { "r": <NumberLong>, "w": <NumberLong>, "R": <NumberLong>, "W": <NumberLong> }, "acquireWaitCount": { "r": <NumberLong>, "w": <NumberLong>, "R": <NumberLong>, "W": <NumberLong> }, "timeAcquiringMicros" : { "r" : Long(0), "w" : Long(0), "R" : Long(0), "W" : Long(0) }, "deadlockCount" : { "r" : Long(0), "w" : Long(0), "R" : Long(0), "W" : Long(0) } }, "ReplicationStateTransition" : { ... }, "Global" : { ... }, "Database" : { ... }, ... } }, ... ], "ok": <num>, "operationTime": <timestamp>, "$clusterTime": <document> }
Exemplos de saída específicos
Estas amostras de saída ilustram currentOp saída para operações específicas. Os campos que compõem a saída real variam dependendo do papel do servidor.
Exemplo de saída de refragmentação
{ shard: '<string>', totalCopyTimeElapsedSecs: Long('<count>'), totalApplyTimeElapsedSecs: Long('<count>'), totalCriticalSectionTimeElapsedSecs: Long('<count>'), totalIndexBuildTimeElapsedSecs: Long('<count>'), indexesToBuild: Long('<count>'), indexesBuilt: Long('<count>'), oplogEntriesFetched: Long('<count>'), oplogEntriesApplied: Long('<count>'), insertsApplied: Long('<count>'), updatesApplied: Long('<count>'), deletesApplied: Long('<count>'), type: 'op', desc: 'ReshardingMetrics{Donor|Recipient|Coordinator}Service <reshardingUUID>', op: 'command', ns: '<database>.<collection>', originatingCommand: { reshardCollection: '<database>.<collection>', key: '<shardkey>', unique:'<boolean>', collation: { locale: 'simple' } }, totalOperationTimeElapsedSecs: Long('<count>'), recipientState: '<service state>', remainingOperationTimeEstimatedSecs: Long('<count>'), approxDocumentsToCopy: Long('<count>'), approxBytesToCopy: Long('<count>'), bytesCopied: Long('<count>'), countWritesToStashCollections: Long('<count>'), documentsCopied: Long('<count>'), provenance: 'reshardCollection' }
Campos de Saída
For a complete list of db.currentOp() output fields, see currentOp.