1

I have a lot of data to fetch from a mongodb database. I can't load all the data at once on the server because it's too big and I would run out of memory.

If I use forEach, will it fetch everything and load everything on the server then apply the function on each of them?

OR

Will it fetch the first element, apply function, load second element, apply function... until the last one?

RainingChain
  • 7,397
  • 10
  • 36
  • 68
  • If you are about `cursor` method `.forEach()` then it should iterate each fetched document in queue. You can find more info about cursor iteration here http://docs.mongodb.org/manual/tutorial/iterate-a-cursor/ – monkeyinsight Oct 03 '14 at 15:45

1 Answers1

3

No it does not load everything. Here is basically why:

> db.hotel.find().forEach
function ( func ){
    while ( this.hasNext() )
        func( this.next() );
}

So you see that "under the hood" all this is doing is providing a "convenience" wrapper over the standard cursor iterator methods.

It's just a helper, whether in the shell or in general driver functions.

But if your "driver" allows, then use a "streaming" interface instead, which is a much better approach.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • so you are saying this is true "Will it fetch the first element, apply function, load second element, apply function... until the last one?" – arcom Oct 18 '17 at 18:14