Introduction to MongoDB cursor.maxTimeMS() Method

MongoDB is a non-relational database that supports multiple programming languages and provides many methods of operation. Among them, the cursor.maxTimeMS() method is a very useful method that can set the maximum time (in milliseconds) for an operation, and the operation will be forcibly terminated if it exceeds this time.

Syntax

The cursor.maxTimeMS() method is an option for the find() and aggregate() methods. The syntax is as follows:

db.collection.find(query).maxTimeMS(time)
db.collection.aggregate(pipeline).maxTimeMS(time)

Here, query is the query condition, pipeline is the aggregation pipeline, and time is the maximum time (in milliseconds) for the operation.

Use cases

When we perform some very time-consuming operations, such as querying a very large collection, we can use the cursor.maxTimeMS() method to avoid the operation running continuously, leading to resource exhaustion. By setting the maximum time, we can ensure that the operation can obtain results within a certain time, and avoid excessive occupation of system resources.

Examples

Here are two examples of using the cursor.maxTimeMS() method.

  1. Query a very large collection and set the maximum time to 10 seconds.

    db.collection.find({}).maxTimeMS(10000)
    
  2. Perform an aggregation operation on a very large collection and set the maximum time to 20 seconds.

    db.collection
      .aggregate([
        {
          $group: {
            _id: "$category",
            total: { $sum: "$price" }
          }
        }
      ])
      .maxTimeMS(20000)
    

Conclusion

By using this method, we can set the maximum time for an operation to avoid the operation running continuously, leading to excessive occupation of system resources. At the same time, we need to be aware that setting a too-short maximum time may result in the operation not being completed, so we need to set the maximum time reasonably according to the actual situation.