Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - dont understand how to loop through collections with a cursor

advertisers = db.dbname.find( 'my query which returns things correctly' );

I realize now that it returns a cursor to the list of collections.

But I am not sure how to loop through them and get each collection.

I want to try something like this:

advertisers.each(function(err, advertiser) {
    console.log(advertiser);
});

But that does not work. But I didn't see from searching online how to make it actually work with simple JavaScript.

Then I have this code:

var item;

if ( advertisers != null )
{
   while(advertisers.hasNext()) 
   { 
      item = advertisers.next();
   }
}

and it gives this error: SyntaxError: syntax error (shell):1

Help much appreciated!

Thanks!

like image 738
Genadinik Avatar asked Jun 05 '12 20:06

Genadinik


1 Answers

The quick and dirty way is:

var item;
var items = db.test.find();
while(items.hasNext()) {
   item = items.next();
   /* Do something with item */
}

There is also the more functional:

items.forEach(function(item) {
   /* do something */
});
like image 131
Justin Thomas Avatar answered Sep 29 '22 12:09

Justin Thomas