MongoDB: forEach vs fetch + each

When I want to iterate over some set of documents stored in MongoDB from my Meteor application, I can use

db.collection.find( ... ).forEach( function f( doc ){ ... })

or

var docs = db.collection.find( ... ).fetch();
_.each( docs, function f( doc ){ ... }); // using underscore.js

Which method is preferable in terms of performance? What are the pros and cons for both options?

+4
source share
1 answer

Both operators do basically the same thing at the core API level, which gets the cursor and converts the results. However, there is one “main” performance difference:

  • .forEach() will broadcast the results of the cursor "one at a time" and process the iterator function it performs.

  • .fetch(), , "" " ", , " " .

, , "" "" . , "" , " " , .fetch() "" .

, - " ", " " . , .fetch() _.each() , . ", " " , , ," " ".

"", , . , , .

" ". .fetch() , .

+3

Source: https://habr.com/ru/post/1598309/


All Articles