In MongoDB, the cursor.forEach() method iterates the cursor to apply a JavaScript function to each document from the cursor.
Syntax
The syntax goes like this:
db.collection.find().forEach(<function>)
Where collection is the name of the collection that the documents reside in.
The <function> signature includes a single argument that is passed the current document to process.
Example
Suppose we have a collection called products that contains the following three documents:
{ "_id" : 1, "product" : "Left Handed Screwdriver" }
{ "_id" : 2, "product" : "Left Blinker" }
{ "_id" : 3, "product" : "Long Weight" }
We can use the forEach() method in conjunction with the find() method to iterate through those documents, while applying a JavaScript function to each document.
Example:
db.products.find().forEach(
function(p) {
print(
p.product.replace("Left","Right")
);
}
);
Result:
Right Handed Screwdriver Right Blinker Long Weight
Error?
If you get an error, like this:
uncaught exception: TypeError: db.products.findOne(...).forEach is not a function : @(shell):1:1
Be sure that you’re using find() and not findOne().
The findOne() method returns the actual document and not a cursor. Therefore, forEach() won’t work with findOne(). Also, even if it did work, findOne() only returns a single document, and therefore, there would be no need to iterate through multiple documents.