50
MongoDBERRORNotableQuery ErrorHIGH confidence

Operation exceeded the specified time limit

What this means

This error indicates that an operation was intentionally terminated by MongoDB because it exceeded the time limit set by the `maxTimeMS` parameter. It is a fail-safe mechanism to prevent long-running queries from impacting database performance.

Why it happens
  1. 1A complex aggregation pipeline that takes too long to execute
  2. 2A query that cannot use an index effectively, resulting in a full collection scan
  3. 3High server load or lock contention, causing the operation to wait and exceed its time limit
  4. 4A `maxTimeMS` value that is set too low for a legitimately complex query
How to reproduce

A `find` query is given a very short time limit, which it exceeds while scanning the collection.

trigger — this will error
trigger — this will error
// Create a large collection
for (let i = 0; i < 200000; i++) { db.data.insertOne({ x: i }) }

// This query will likely exceed 5ms because it cannot use an index for the $where clause.
db.data.find({ $where: "sleep(1); return true;" }).maxTimeMS(5);

expected output

MongoServerError: operation exceeded time limit

Fix 1

Optimize the Query or Aggregation

WHEN The operation is inefficient.

Optimize the Query or Aggregation
// Create an index to support the query predicate.
db.data.createIndex({ x: 1 });

// The optimized query can use the index and will be much faster.
db.data.find({ x: { $gt: 100000 } }).maxTimeMS(1000);

Why this works

The best solution is to make the query faster. Use `explain()` to analyze the query plan and identify bottlenecks. Adding appropriate indexes is the most common way to resolve performance issues.

Fix 2

Increase the `maxTimeMS` Value

WHEN The query is already optimized but requires more time to run.

Increase the `maxTimeMS` Value
// Increase the time limit for a known long-running, but necessary, operation.
db.data.aggregate([...]).maxTimeMS(60000); // 1 minute

Why this works

If an operation is complex and cannot be optimized further (e.g., a large reporting aggregation), you can increase the `maxTimeMS` value. Do this on a per-operation basis rather than globally.

Fix 3

Break Down the Operation

WHEN You are processing a large dataset.

Why this works

Instead of a single query that processes millions of documents, break it into smaller batches. For example, process documents month by month in a loop instead of all at once.

What not to do

Remove `maxTimeMS` entirely without optimizing the query

This simply allows the slow query to run indefinitely, which can degrade the performance of the entire database cluster for all other clients. The time limit is a safety feature.

Sources
Official documentation ↗

mongodb/mongo src/mongo/base/error_codes.yml

Terminate Running Operations

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MongoDB errors