This section covers how to get detailed information on operations, index usage, replication status, and more.
Viewing and Killing Operations
You can see current operations with the currentOp
function:
> db.currentOp()
{
"inprog" : [
{
"opid" : 123,
"active" : false,
"locktype" : "write",
"waitingForLock" : false,
"secs_running" : 200,
"op" : "query",
"ns" : "foo.bar",
"query" : {
}
...
},
...
]
}
Using the opid
field from above, you can kill operations:
Not all operations can be killed or will be killed immediately. In general, operations that are waiting for a lock cannot be killed until they acquire the lock.
Index Usage
Use explain()
to see which index MongoDB is using for a query. verbosity
specifies the mode, which determines the amount of returned information. Possible modes include allPlansExecution
(default), queryPlanner
, and executionStats
.
> db.runCommand({
explain: {
count: "users",
query: { age: { $gt: 30 } },
},
verbosity: "queryPlanner",
});
{
explainVersion: '1',
queryPlanner: {
namespace: 'test.users',
indexFilterSet: false,
maxIndexedOrSolutionsReached: false,
maxIndexedAndSolutionsReached: false,
maxScansToExplodeReached: false,
winningPlan: { stage: 'COUNT', inputStage: { stage: 'EOF' } },
rejectedPlans: []
},
command: { count: 'users', query: { age: { '$gt': 30 } }, '$db': 'test' },
serverInfo: {
host: 'bdc9e348c602',
port: 27017,
version: '7.0.4',
gitVersion: '38f3e37057a43d2e9f41a39142681a76062d582e'
},
serverParameters: {
internalQueryFacetBufferSizeBytes: 104857600,
internalQueryFacetMaxOutputDocSizeBytes: 104857600,
internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600,
internalDocumentSourceGroupMaxMemoryBytes: 104857600,
internalQueryMaxBlockingSortMemoryUsageBytes: 104857600,
internalQueryProhibitBlockingMergeOnMongoS: 0,
internalQueryMaxAddToSetBytes: 104857600,
internalDocumentSourceSetWindowFieldsMaxMemoryBytes: 104857600,
internalQueryFrameworkControl: 'trySbeEngine'
},
ok: 1
}
There are several important fields in the output of explain()
:
explainVersion
is the output format version.
command
is the command being explained.
queryPlanner
provides information about the selected and rejected plans by the query optimizer.
executionStats
provides execution details of the accepted and rejected plans.
serverInfo
provides information about the MongoDB instance.
serverParameters
provides details about the internal parameters.
Types of Cursors
Here are some common cursor types in MongoDB:
- Standard cursor is the default type returned by
db.collection.find()
. It iterates over query results in batches, retrieving data on demand from the server.
- Change Stream cursor is a real-time data monitor, notifying you whenever a document in a collection is inserted, updated, deleted, or replaced.
- Tailable cursor is a cursor for a capped collection that remains open after the client exhausts the results in the initial cursor.
- Backup cursor is a type of tailable cursor that points to a list of backup files. Backup cursors are for internal use only.
- Orphaned cursor is a cursor that is not correctly closed or iterated over in your application code. It can cause performance issues.
Hinting
Use hint()
to force a particular index to be used for a query:
> db.foo.find().hint({x:1})
System Profiling
You can turn on system profiling to see operations currently happening on a database. Note that there is a performance penalty to profiling, but it can help isolate slow queries.
> db.setProfilingLevel(2) // profile all operations
> db.setProfilingLevel(1) // profile operations that take longer than 100ms
> db.setProfilingLevel(1, 500) // profile operations that take longer than 500ms
> db.setProfilingLevel(0) // turn off profiling
> db.getProfilingLevel(1) // see current profiling setting
Profile entries are stored in a capped collection called system.profile
within the database in which profiling was enabled. Profiling can be turned on and off for each database.
Replica Sets
To find replication lag information for each secondary node, connect to the primary node of the replica set and run this command:
> rs.printSecondaryReplicationInfo()
source: m1.demo.net:27002
syncedTo: Mon Feb 01 2023 10:20:40 GMT-0800 (PST)
20 secs (0 hrs) behind the primary
The above command prints a formatted output of the replica set status. You can also use db.printReplicationInfo()
to retrieve the replica set member's oplog. Its output is identical to that of rs.printReplicationInfo()
.
To see a member's view of the entire set, connect to it and run the following command:
This command returns a structured JSON output and shows you what it thinks the state and status of the other members are. Running rs.status()
on a secondary node will show you which node the secondary is syncing from in the syncSourceHost
field.
Sharding
To see your cluster's metadata (shards, databases, chunks, etc.), execute the following command from the MongoDB shell (mongosh
) connected to any member of the sharded cluster:
> db.printShardingStatus()
If verbosity is set to true
, it displays full details of the chunk distribution across shards along with the number of chunks on each shard:
> db.printShardingStatus(true)
sh.status
can also be executed on a mongos
instance to fetch sharding configuration. Its output is the same as that of printShardingStatus
:
You can also connect to the mongos
and see data about your shards, databases, collections, or chunks by using use config
, then querying the relevant collections:
> use config
switched to db config
> show collections
changelog
chunks
collections
csrs.indexes
databases
migrationCoordinators
mongos
rangeDeletions
settings
shards
tags
version
Always connect to a mongos
to get sharding information. Never connect or write directly to a config
server; always use sharding commands and helpers.
After maintenance, sometimes mongos
processes that were not actually performing the maintenance will not have an updated version of the config. Either bouncing these servers or running the flushRouterConfig
command is generally a quick fix to this issue:
> use admin
> db.runCommand({flushRouterConfig:1})
Often this problem will manifest as setShardVersion
failed errors. Don't worry about setShardVersion
errors in the logs, but they should not trickle up to your application. Note that you shouldn't get the errors from a driver unless the mongos
it's connecting to cannot reach any config
servers.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}