Home » Software Development » MongoDB » MongoDB hasNext() and next() Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

MongoDB hasNext() and next() Example

Hello readers, in this tutorial, we will see the hasNext() and the next() 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 hasNext() and the next() 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 hasNext() and next() Example

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

2.1 hasNext() method in the Mongo database

In the Mongo universe, the hasNext() method returns true if the cursor object returned by the db.collection.find() query has more documents to return. If not, the hasNext() method will return a Boolean false. This method has the following prototype form:

Mongo database ‘hasNext()’ Syntax

> db.collection_name.find(<query_string>).hasNext()

Where:

  • The query_string is an optional input argument that retrieves the documents from the collection on the basis of a specified selection criteria

Do remember, this method returns a Boolean output.

2.2 next() method in the Mongo database

In the Mongo universe, the next() method returns the next document in a cursor object returned by the db.collection.find() query. This method has the following prototype form:

Mongo database ‘next()’ Syntax

> db.collection_name.find(<query_string>).next()

Where:

  • The query_string is an optional input argument that retrieves the documents from the collection on the basis of a specified selection criteria

Do remember, this method returns an exception if the next() method has no document in the cursor object.

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" : "1001", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone", "price" : 200, "warranty_years" : 1, "available" : "true" },
	{ "_id" : "1002", "name" : "AC7 Phone", "brand" : "ACME", "type" : "phone", "price" : 320, "warranty_years" : 1, "available" : "false" },
	{ "_id" : "1003", "name" : "AC3 Series Charger", "type" : [ "accessory", "charger" ], "price" : 19, "warranty_years" : 0.25, "for" : [ "ac3", "ac7", "ac9" ] },
	{ "_id" : "1004", "name" : "AC3 Case Green", "type" : [ "accessory", "case" ], "color" : "green", "price" : 12, "warranty_years" : 0 },
	{ "_id" : "1005", "name" : "Phone Extended Warranty", "type" : "warranty", "price" : 38, "warranty_years" : 2, "for" : [ "ac3", "ac7", "ac9", "qp7", "qp8", "qp9" ] },
	{ "_id" : "1006", "name" : "AC3 Case Black", "type" : [ "accessory", "case" ], "color" : "black", "price" : 12.5, "warranty_years" : 0.25, "available" : "false", "for" : "ac3" },
	{ "_id" : "1007", "name" : "AC3 Case Red", "type" : [ "accessory", "case" ], "color" : "red", "price" : 12, "warranty_years" : 0.25, "available" : "true", "for" : "ac3" },
	{ "_id" : "1008", "name" : "Phone Service Basic Plan", "type" : "service", "monthly_price" : 40, "limits" : { "voice" : { "units" : "minutes", "n" : 400, "over_rate" : 0.05 }, "data" : { "units" : "gigabytes", "n" : 20, "over_rate" : 1 }, "sms" : { "units" : "texts sent", "n" : 100, "over_rate" : 0.001 } }, "term_years" : 2 },
	{ "_id" : "1009", "name" : "Phone Service Core Plan", "type" : "service", "monthly_price" : 60, "limits" : { "voice" : { "units" : "minutes", "n" : 1000, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "term_years" : 1 },
	{ "_id" : "1010", "name" : "Phone Service Family Plan", "type" : "service", "monthly_price" : 90, "limits" : { "voice" : { "units" : "minutes", "n" : 1200, "over_rate" : 0.05 }, "data" : { "n" : "unlimited", "over_rate" : 0 }, "sms" : { "n" : "unlimited", "over_rate" : 0 } }, "sales_tax" : true, "term_years" : 2 },
	{ "_id" : "1011", "name" : "Cable TV Basic Service Package", "type" : "tv", "monthly_price" : 50, "term_years" : 2, "cancel_penalty" : 25, "sales_tax" : "true", "additional_tariffs" : [ { "kind" : "federal tariff", "amount" : { "percent_of_service" : 0.06 } }, { "kind" : "misc. tariff", "amount" : 2.25 } ] }
] )

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 Implementation of ‘hasNext()’ method

Now, go back to the Mongo shell and use the hasNext(<query_string>) method to check if the cursor object has more documents to return.

Query 1

> db.products.find().hasNext()

This command will return a Boolean true because the db.products.find() cursor object has more documents to return.

Fig. 6: Mongo database hasNext() method

Fig. 6: Mongo database hasNext() method

Let’s say developers want to return the documents that match criteria. They can achieve this by simply appending the selection criteria in the find() method. Let’s understand this with the help of an example.

Query 1(a)

> db.products.find( { "available" : "true", "brand": "ACME_NEW" } ).hasNext()

This command will return a Boolean false because the criteria specified in the db.products.find() cursor object has no documents to return.

Fig. 7: Mongo database hasNext() method with selection criteria

Fig. 7: Mongo database hasNext() method with selection criteria

2.3.6 Implementation of ‘next()’ method

Refresh the Mongo shell and use the next(<query_string>) method to return the next document in a cursor.

Query 2

> db.products.find().next()

This command will return the next document from the products collection.

Fig. 8: Mongo database next() method

Fig. 8: Mongo database next() method

Let’s say developers want to retrieve the documents from a collection that matches criteria. They can modify the Query 2 as shown below.

Query 2 (a)

> db.products.find( { "available" : "false", "brand": "ACME" } ).next()

This command will return the output as shown in Fig. 9.

Fig. 9: Mongo database next() method with selection criteria

Fig. 9: Mongo database next() method with selection criteria

Do remember, this method will return an exception if the next() method has no document in the cursor object. Let’s understand this with the help of an example.

Exception Trace

> db.products.find( { "available" : "false", "brand": "PHILIP" } ).next()

2018-03-07T21:14:45.096+0530 E QUERY    [thread1] Error: error hasNext: false :
DBQuery.prototype.next@src/mongo/shell/query.js:305:1
@(shell):1:1

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

3. Conclusion

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

Download
You can download the full source code of this example here: CodeSnippet
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of