How to accumulate results (with foreach?) in mongodb?

by herminia_bruen , in category: MySQL , a month ago

How to accumulate results (with foreach?) in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a month ago

@herminia_bruen 

In MongoDB, you can use the forEach method to iterate over each document in a collection and accumulate the results. Here is an example of how you can use forEach to accumulate results in MongoDB:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let total = 0;

db.collection('yourCollectionName').find().toArray(function(err, results) {
  if (err) {
    console.log(err);
    return;
  }

  results.forEach(function(doc) {
    total += doc.fieldName; // Accumulate the results here
  });

  console.log("Total: ", total);
});


In this example, total is initialized outside of the forEach loop and then incremented by the value of a field in each document in the collection. Finally, the total is printed to the console once all documents have been processed.


You can modify the accumulator logic inside the forEach loop as needed to accumulate the results based on your requirements.