mark
mark

Reputation: 62774

Is it possible to iterate a mongo cursor twice?

In other words, is there a way to rewind it to the beginning?

EDIT

I am using mongo shell and pymongo.

Upvotes: 18

Views: 12831

Answers (3)

Irshad Khan
Irshad Khan

Reputation: 6046

You can use cursor.reset();

For PHP : $cursor->reset();

then run your foreach($cursorData as $data) any time after resetting.

Upvotes: 1

EwyynTomato
EwyynTomato

Reputation: 4077

Cursor in pymongo has .rewind() method, you can refer to sample code from previous question with answer that apply.

Native mongo shell api, however, doesn't provide such method, see method help() on DBQuery object prototype.:

> db.collection.find().help()
find() modifiers
        .sort( {...} )
        .limit( n )
        .skip( n )
        .count() - total # of objects matching query, ignores skip,limit
        .size() - total # of objects cursor would return, honors skip,limit
        .explain([verbose])
        .hint(...)
        .showDiskLoc() - adds a $diskLoc field to each returned object

Cursor methods
        .forEach( func )
        .map( func )
        .hasNext()
        .next()

Upvotes: 2

brice
brice

Reputation: 25039

The Ruby API has the rewind! method that does exactly what you want.

The Python API also has the cursor.rewind() method.

The PHP API also has the cursor.rewind() method.

However, neither the Java or C++ APIs have the rewind method. All can be found from the official API page.

Upvotes: 31

Related Questions