Terminate Running Operations
Overview
MongoDB provides two facilitates to terminate running operations:maxTimeMS()
and db.killOp()
. Use theseoperations as needed to control the behavior of operations in aMongoDB deployment.
Available Procedures
maxTimeMS
New in version 2.6.
The maxTimeMS()
method sets a time limit for anoperation. When the operation reaches the specified time limit,MongoDB interrupts the operation at the next interrupt point.
Terminate a Query
From the mongo
shell, use the following method to set atime limit of 30 milliseconds for this query:
- db.location.find( { "town": { "$regex": "(Pine Lumber)",
- "$options": 'i' } } ).maxTimeMS(30)
Terminate a Command
Consider a potentially long running operation usingdistinct
to return each distinct collection
field thathas a city
key:
- db.runCommand( { distinct: "collection",
- key: "city" } )
You can add the maxTimeMS
field to the command document to set atime limit of 45 milliseconds for the operation:
- db.runCommand( { distinct: "collection",
- key: "city",
- maxTimeMS: 45 } )
db.getLastError()
and db.getLastErrorObj()
will returnerrors for interrupted options:
- { "n" : 0,
- "connectionId" : 1,
- "err" : "operation exceeded time limit",
- "ok" : 1 }
killOp
The db.killOp()
method interrupts a running operation atthe next interrupt point. db.killOp()
identifiesthe target operation by operation ID.
- db.killOp(<opId>)
Warning
Terminate running operations with extreme caution. Only usedb.killOp()
to terminate operations initiated by clientsand do not terminate internal database operations.
Sharded Cluster
Starting in MongoDB 4.0, the killOp
command can be run ona mongos
and can kill queries (i.e. read operations)that span shards in a cluster. The killOp
command from themongos
does not propagate to the shards when theoperation to be killed is a write operation.
For more information on killing operations on a sharded cluster, see:
For information on how to list sharding operations that are active on amongos
, see the localOps
parameter in$currentOp
.