Home » Software Development » MongoDB » MongoDB forEach() 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 forEach() Example

Hello readers, in this tutorial, we will understand the cursor.forEach() method available in the Mongo database. Let’s study in brief the role and the usage of this method.

1. Introduction

If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the cursor.forEach() 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 features.

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.2 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.3 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 representation lists 4 documents in a collection where the cursor will point to the first document and then iterate through all the documents of a collection.

Fig. 1: Pictorial representation of a Cursor in Mongo collection

Fig. 1: Pictorial representation of a Cursor in Mongo collection

2. MongoDB forEach Example

In this tutorial, we will learn how to handle the cursor.forEach() method provided by the Mongo database. But before moving further with the tutorial, we will need to create the sample collection. The following script creates a database called warehouse with a collection as editors. Open the Mongo terminal and execute the script.

> use warehouse

> db.editors.insertMany( [
	{ "_id" : "101", "full_name" : "Daniel Atlas" }, 
	{ "_id" : "102", "full_name" : "Charlotte Neil" },
	{ "_id" : "103", "full_name" : "James Breen" },
	{ "_id" : "104", "full_name" : "John Gordon" },
	{ "_id" : "105", "full_name" : "Rick Ford" },
	{ "_id" : "106", "full_name" : "Susan Dixit" },
	{ "_id" : "107", "full_name" : "John Snow" },
	{ "_id" : "108", "full_name" : "Arya Stark" },
	{ "_id" : "109", "full_name" : 25 },
	{ "_id" : "110", "full_name" : "John Daniel" }
] )

> db.editors.find().pretty()

If everything goes well, the database and the collection will be shown in the Mongo Workbench.

Fig. 2: Database & Collection Creation

Fig. 2: Database & Collection Creation

2.1 forEach() method in the Mongo database

In the Mongo universe, the forEach() method allows the developer to apply a JavaScript function for each document in a cursor. Developers can use the forEach() loop to perform the basic activities like:

    • Updating the documents using the forEach() method
    • Deleting the documents using the forEach() method
    • Manipulating the value of the documents using the forEach() method

Here is what the query syntax will look like.

Syntax

> db.collection_name.find().forEach( <JavaScript_function> )

Where:

  • A JavaScript_function is applied to each document from the cursor. Do note, this JavaScript method requires a single input argument for processing

Let’s understand this with the help of an example.

Query 1

> db.editors.find().forEach( function(myDoc) { print( "User: " + myDoc.full_name ); } )

This command prints the name of each user in a collection by invoking the forEach() method on the cursor object returned by the Mongo database find() method.

Fig. 3: Mongo database forEach() method

Fig. 3: Mongo database forEach() method

Now, let’s move further and understand how to update a field value using the forEach() loop. Let’s understand this with the help of an example.

Query 2

> db.editors.find( { full_name: 25 } ).forEach(function(doc) {    
    var updated_name = "Susan Powell";
    db.editors.update( { _id: doc._id }, { $set: { "full_name": updated_name } } );
})

Here we are invoking the forEach() method to update the name of the user that matches the specified criteria. Once this is completed we will check the update query result using the Query 1.

Fig. 4: Mongo database forEach() method for Updating document

Fig. 4: Mongo database forEach() method for Updating document

Another advantage of using the forEach() method is that it allows the developers to remove a document from the Mongo collection. Let’s understand this with the help of an example.

Query 3

> db.editors.find( { full_name: "Susan Powell" } ).forEach(function(doc){
    db.editors.remove( { _id: doc._id } );
})

This command removes the document that matches the specified collection by invoking the forEach method on the cursor object returned by the Mongo database find() method.

Fig. 5: Mongo database forEach() method for Removing document

Fig. 5: Mongo database forEach() method for Removing document

Do note, the pretty() method used in above commands displays the documents in a structured pattern. If developers want to display the output in a non-structured pattern, they can simply remove this method. That’s all for this post. Happy Learning!!

3. Conclusion

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

Download
You can download the full source code of this example here: MongoDbForEachMethod
(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