MongoDB

MongoDB max() and min() Example

Hello readers, in this tutorial, we will see the max() and min() methods 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 max() and min() methods 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.

Fig. 1: Pictorial representation of a Cursor in Mongo collection
Fig. 1: Pictorial representation of a Cursor in Mongo 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 max() and min() Example

In this tutorial, we will learn how to handle the max() and min() methods provided by the Mongo database.

2.1 max() method in the Mongo database

In the Mongo universe, the max() method specifies an exclusive upper bound for a particular index to drive the results of the db.collection_name.find() query. This method provides a way to specify an upper bound on the compound key indexes. The cursor.max() method has the following prototype form:

Mongo database ‘max()’ Syntax

> db.collection_name.find().max(<indexBounds>)

Where:

  • The indexBounds is a ‘document’ type input argument that exclusively specifies the upper bound for the index keys. This input argument value has the following prototype form:
    { field1: <max value>, field2: <max value2> ... fieldN:<max valueN> }
    

Do remember:

  • The max() method requires an index on a field and forces the Mongo query to use this index
  • The max() method primarily exists to support the sharding process in the Mongo database
  • If developers use the max() method with min(), they should note that the index bounds specified in the max() and min() methods must refer to the keys of the same index

2.2 min() method in the Mongo database

In the Mongo universe, the min() method specifies an inclusive lower bound for a particular index to drive the results of the db.collection_name.find() query. This method provides a way to specify a lower bound on the compound key indexes. The cursor.min() method has the following prototype form:

Mongo database ‘min()’ Syntax

> db.collection_name.find().min(<indexBounds>)

Where:

  • The indexBounds is a ‘document’ type input argument that inclusively specifies the lower bound for the index keys. This input argument value has the following prototype form:
    { field1: <max value>, field2: <max value2> ... fieldN:<max valueN> }
    

Do remember:

  • The min() method requires an index on a field and forces the Mongo query to use this index
  • The min() method primarily exists to support the sharding process in the Mongo database
  • If developers use the min() method with max(), they should note that the index bounds specified in the min() and max() methods must refer to the keys of the same index

2.3 Practical usage

Let’s understand the implementation of these methods with the help of the sample snippets.

2.3.1 Start MongoDB

Start a standalone mongod instance as shown below.

Fig. 2: Start Mongo instance
Fig. 2: Start Mongo instance

2.3.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.

Fig. 3: Connect to Mongo database
Fig. 3: Connect to Mongo database

2.3.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.

Fig. 4: Database & Collection creation
Fig. 4: Database & Collection creation

2.3.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.

Fig. 5: Mongo database & collection
Fig. 5: Mongo database & collection

2.3.5 Get Indexes

To use the Mongo database max() and min() cursor functions, we will need to make sure that an index already exists in the products collection as shown below.

Fig. 6: Get Indexes for the 'products' collection
Fig. 6: Get Indexes for the ‘products’ collection

2.3.6 Implementation of ‘max()’ method

Now, go back to the Mongo shell and use the max(<indexBounds>) method to understand it’s practical implementation in the Mongo world. The below example returns the Mongo documents that are below the index key bound of item equal to mango and type equal to jonagold.

Query 1

> db.products.find().max( { item: 'mango', type: 'jonagold' } ).hint( { item: 1, type: 1 } )

The Query 1 snippet will return the following Mongo documents as shown in Fig. 7.

Fig. 7: Mongo database max() method
Fig. 7: Mongo database max() method

2.3.7 Implementation of ‘min()’ method

The below example returns the Mongo documents that are at or above the index key bound of item equal to mango and type equal to jonagold.

Query 2

> db.products.find().min( { item: 'mango', type: 'jonagold' } ).hint( { item: 1, type: 1 } )

The Query 2 snippet will return the following Mongo documents as shown in Fig. 8.

Fig. 8: Mongo database min() method
Fig. 8: Mongo database min() method

Do note:

  • If the Query 1 and 2 did not explicitly specify the index with the hint() method, it would be ambiguous for the Mongo instance to either select the { item: 1, type: 1 } index ordering or the { item: 1, type: -1 } index ordering

2.3.8 Implementation of ‘max()’ and ‘min()’ methods

Let’s say developers want to use the ordering of index { cost: 1 }. They can run this scenario by using the min() and max() methods in a single query where:

  • min() method will limit the Mongo documents that are at or above the index key bound of price equal to 1.39 and,
  • max() method will limit the Mongo documents that are below the index key bound of price equal to 1.99

The following Mongo database command can be used to explain this.

Query 3

> db.products.find().min( { cost: 1.39 } ).max( { cost: 1.99 } ).hint( { cost: 1 } )

The Query 3 snippet will return the following Mongo document as shown in Fig. 9.

Fig. 9: Mongo database min() method
Fig. 9: Mongo database min() method

That’s all for this post. Happy Learning!!

3. Conclusion

In this tutorial, we learned about the max() and min() methods 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 max() and min() methods method available in the Mongo database.

Download
You can download the full source code of this example here: CodeSnippet

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Yustas
Yustas
3 years ago

Well… but how do I select min() from the collection in Java Code?
For example:

import ...
public class MongoDBtest {

  public static void main(String[] args) {
    MongoClient mongoClient = new MongoClient( "127.0.0.1" , 27017 );

    MongoDatabase database = mongoClient.getDatabase("my_books");

    MongoCollection<Document> collection = database.getCollection("books");

    collection.drop();

    Document book1 = new Document()
        .append("Book_title", "The Glass Bead Game")
        .append("Author", "Hermann Hesse")
        .append("Year_of_publication", 1971);

    Document book2 = new Document()
        .append("Book_title", "The Sea-Wolf")
        .append("Author", "Jack London")
        .append("Year_of_publication", 1965);
etc.....
    Document bookN 

How can I choose a book with the oldest year of publication?

Back to top button