Introduction to MongoDB cursor.forEach() Method

The forEach() method is one of the methods in MongoDB used to iterate over query results. It allows developers to perform custom iteration operations on query results, such as calculation, filtering, formatting, and so on. This article will introduce the use of forEach() method from four aspects: syntax, use cases, examples, and conclusions.

Syntax

The syntax of the forEach() method is as follows:

db.collection.find().forEach(function)

Here, cursor is the cursor object in MongoDB, and function is a callback function used to perform custom operations on query results.

Use Cases

The forEach() method is suitable for scenarios where custom iteration operations are required on query results, such as calculating the total number of query results, formatting query results, and so on. In practical applications, the forEach() method is often used in conjunction with other MongoDB query methods, such as find(), aggregate(), and so on.

Examples

Example 1

The following is an example of using the forEach() method to perform custom operations on query results:

Assume we have a collection named users that contains some user information such as username, age, gender, and so on. We can use the following code to query users whose age is greater than or equal to 18, and calculate their average age:

var totalAge = 0
var count = 0

db.users.find({ age: { $gte: 18 } }).forEach(function (user) {
  totalAge += user.age
  count++
})

var avgAge = totalAge / count

print("The average age of users over 18 is " + avgAge)

In this example, we first define two variables totalAge and count to save the total age and the number of users. Then, we use the find() method to query users whose age is greater than or equal to 18, and use the forEach() method to iterate over the query results. In the iteration operation, we accumulate the age of each user and add 1 to the number of users. Finally, we calculate the average age based on the accumulated total age and the number of users, and use the print() method to output the result.

Example 2

The following is an example of using the forEach() method to format query results:

Assume we have a collection named articles that contains some article information such as title, author, publication date, and so on. We can use the following code to query the 5 most recently published articles and format them as HTML:

var html = ""

db.articles
  .find()
  .sort({ date: -1 })
  .limit(5)
  .forEach(function (article) {
    html += "<h1>" + article.title + "</h1>"
    html +=
      "<p>Published by " +
      article.author +
      " on " +
      article.date.toDateString() +
      "</p>"
    html += "<p>" + article.content + "</p>"
    html += "<hr>"
  })

print(html)

In this example, we first define a variable html to save the formatted HTML code. Then, we use the find() method to query all articles and sort them in reverse order by publication date. Next, we use the limit() method to limit the number of query results to 5. Finally, we use the forEach() method to iterate over the query results and add the title, author, and publication date of each article in HTML format to the html variable.

Conclusion

Through the introduction in this article, we have learned about the basic syntax, usage scenarios, examples, and conclusions of the forEach() method in MongoDB. The forEach() method can iterate over each document in the query results and perform specific operations on each document, such as formatting and modification of the query results. At the same time, we need to be careful when using the forEach() method to avoid performing operations on a large number of documents, which may affect performance.