Para agentes de IA: um índice de documentação está disponível em https://www.mongodb.com/pt-br/docs/llms.txt — as versões de markdown de todas as páginas estão disponíveis anexando .md a qualquer caminho de URL.
Menu Docs

db.currentOp() (método mongosh)

db.currentOp()

Importante

We recommend using the $currentOp aggregation stage instead of the currentOp command (deprecated with version 6.2) and the db.currentOp() method.

Returns a document that contains information on in-progress operations for the database instance. The db.currentOp() method wraps the database command currentOp.

Observação

Starting in MongoDB 5.0, the $currentOp aggregation stage is used when running the helper method db.currentOp() with mongosh.

Given this, in the 5.0 version of the shell and with mongosh, db.currentOp() result sets are not subject to the 16MB BSON document return size document return size limit for documents of the previous legacy mongo versions.

Esse método está disponível em implantações hospedadas nos seguintes ambientes:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

Importante

This command is not supported in M0 and Flex clusters. For more information, see Unsupported Commands.

  • 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

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:

  • Especifique true para incluir operações em conexões ociosas e operações do sistema.

  • Specify a document with query conditions to report only on those operations that match the conditions. See Behavior for details.

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

"$ownOps"

Booleano. Se definido para true, retorna informações somente sobre as operações do usuário atual.

Em instâncias do mongod, os usuários sempre podem executar o db.currentOp( { "$ownOps": true } ) para visualizar suas próprias operações.

"$all"

Booleano. Se definido para true, retorna informações sobre todas as operações, incluindo operações em conexões ociosas e operações do sistema. Para obter mais informações, veja $currentOp (estágio de agregação).

If the document includes "$all": true along with Output Fields conditions, only the "$all":true applies.

<filter>

Especifique as condições de filtro nos Campos de Saída. Veja exemplos.

If the document includes "$all": true along with Output Fields conditions, only the "$all": true applies.

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:

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.

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.

The following examples use the db.currentOp() method with various query documents to filter the output.

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 } }
]
}
)

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
}
)

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\./
}
)

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

As operações de indexação ativas não se aplicam à construção de índice contínua.

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>,
"inUseTrackedMemBytes": <Long()>, // Starting in 8.3
"peakTrackedMemBytes": <Long()>, // Starting in 8.3
"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>
}

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.

{
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'
}

For a complete list of db.currentOp() output fields, see currentOp.