MongoDB maxTimeMS() Example
Hello readers, in this tutorial, we will see the maxTimeMS()
method available in the Mongo database.
1. Introduction
If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the maxTimeMS()
method then follow the below steps. It is very simple, but before moving further let’s take a look at the Mongo database and its characteristics.
1.1 What is MongoDB?
- MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN))
- The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
- Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
- This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability
1.1.1 Why MongoDB?
- As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
- This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
- MongoDB offers indexes to improve the search performance within the NoSQL database
- To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
- Replication: MongoDB can give high availability with the replica sets
1.2 What is a Cursor in MongoDB?
In Mongo world, a cursor is an object that allows developers to iterate through the documents of a Mongo collection. The behavior of cursor allows an automatic iteration across the results of the query; however, developers can explicitly go through the items returned in the cursor object. The below diagram lists 4
documents where the Mongo cursor will point to the first document and then iterate through all the other documents of a collection.
1.2.1 Why Cursor in MongoDB?
Cursor offers:
- A true snapshot of a system i.e. it returns the data in batches and increases the database performance
- It saves system memory by allowing batch inserts and updates
- Intelligibility and Clarity on the ad-hoc and complex queries of the sequential nature having large result sets and low consistency requirements
- Openness to work on small batches of data as developers don’t need to wait for the processing and download of the complete record-set
2. MongoDB maxTimeMS() Example
In this tutorial, we will learn how to handle the cursor.maxTimeMS()
method provided by the Mongo database.
2.1 maxTimeMS() method in the Mongo database
In the Mongo universe, the maxTimeMS()
method specifies a cumulative time limit in milliseconds for processing the operations on a cursor object. The cursor.maxTimeMS()
method has the following prototype form:
Mongo database ‘maxTimeMS()’ Syntax
> db.collection_name.find(<query_string>).maxTimeMS(<time_limit>)
Where:
- The
query_string
is an optional input argument that retrieves the documents from a collection on the basis of a specified choice criteria - The
time_limit
is an input integer argument that specifies the cumulative time limit in milliseconds
Do remember:
- The
cursor.maxTimeMS()
method is different from theNoCursorTimeout
query flag as the cursor method links to the processing time, while query flag links to the idle-time - A cursor’s idle-time does not negotiate towards it’s processing time
2.1.1 Scenarios where maxTimeMS() method would be useful
- Batching of results allow developers to define an amount of time and effort the database need while returning the results until it quits and moves on to the next request. Thus, the cursor object would continue to return the results until the allotted time has expired
- Termination of the target operations which have exceeded their time limit. Mongo database terminates the operations using the same mechanism as the
db.killOp()
method. Do note, these operations will only be terminated at one of its designated interrupt points - Mongo database does not count the network latency towards a cursor’s time limit
2.2 Practical usage
Let’s understand the implementation of this method with the help of the sample snippets.
2.2.1 Start MongoDB
Start a standalone mongod instance as shown below.
2.2.2 Connect to the Mongo Instance
Connect with the mongo shell to make a connection with the MongoDB instance on the port 27017
as shown below.
2.2.3 Create Mongo database and collection
To begin with the implementation, we will need to create a sample database and collection. The below script creates a database called warehouse
with a collection of products
. Open the Mongo terminal and execute the script.
Database & Collection creation script
> use warehouse > db.products.insertMany( [ { "_id" : 5, "item" : "mango", "type" : "cortland", "cost" : 1.29, "warrantyYears" : 1, "available" : false }, { "_id" : 9, "item" : "mango", "type" : "fuji", "cost" : 1.99 }, { "_id" : 7, "item" : "mango", "type" : "honey crisp", "cost" : 1.99, "warrantyYears" : 1, "available" : true }, { "_id" : 10, "item" : "mango", "type" : "jonagold", "cost" : 1.29, "warrantyYears" : 1, "available" : false }, { "_id" : 1, "item" : "mango", "type" : "jonathan", "cost" : 1.29 }, { "_id" : 6, "item" : "mango", "type" : "mcintosh", "cost" : 1.29 }, { "_id" : 8, "item" : "orange", "type" : "cara", "cost" : 2.99 }, { "_id" : 4, "item" : "orange", "type" : "navel", "cost" : 1.39, "warrantyYears" : 1, "available" : true }, { "_id" : 3, "item" : "orange", "type" : "satsuma", "cost" : 1.99 }, { "_id" : 2, "item" : "orange", "type" : "valencia", "cost" : 0.99, "warrantyYears" : 1, "available" : true } ] )
The script gives the below output.
2.2.4 Check Mongo database and collection
If the script works well, the database and the collection will be shown in the Mongo Workbench. Using the db.collection_name.find()
or the db.collection_name.find().pretty()
command the documents of a collection will be shown as below.
2.3.6 Implementation of ‘maxTimeMS()’ method
Now, go back to the Mongo shell and use the maxTimeMS(<time_limit>)
method to understand it’s practical implementation in the Mongo world. The below example specifies a time limit of ‘30 milliseconds‘.
Query 1
> db.products.find().maxTimeMS(30)
The Query 1 snippet will return the following Mongo documents as shown in Fig. 6.
Let’s say developers want to return the documents by specifying a query string. They can do this by simply appending the query_string
in the find()
method. The following Mongo database command can be used.
Query 2
> db.products.find( { "item" : "orange" } ).maxTimeMS(50)
The Query 2 snippet will return the Mongo documents from the products
collection that matches the specified choice criteria as shown in Fig. 7.
Do remember, the cursor.maxTimeMS()
method will return an exception if the Mongo query exceeds the specified time limit. Let’s understand this with the help of an example.
Exception Trace
> db.products.find( { "item" : "orange" } ).maxTimeMS(30) Error: error: { "ok" : 0, "errmsg" : "errmsg: \"operation exceeded time limit\"", "code" : 50, "codeName" : "ExceededTimeLimit" }
That’s all for this post. Happy Learning!!
3. Conclusion
In this tutorial, we learned about the maxTimeMS()
method of the Mongo database. Developers can download the sample commands in the Downloads section.
4. Download the Eclipse Project
This was an example of the maxTimeMS()
method available in the Mongo database.
You can download the full source code of this example here: CodeSnippet