Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate a mongo cursor twice?

Tags:

mongodb

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

EDIT

I am using mongo shell and pymongo.

like image 963
mark Avatar asked Mar 26 '12 13:03

mark


People also ask

How do MongoDB cursors work?

The Cursor is a MongoDB Collection of the document which is returned upon the find method execution. By default, it is automatically executed as a loop. However, we can explicitly get specific index document from being returned cursor. It is just like a pointer which is pointing upon a specific index value.

Do I need to close MongoDB cursor?

Closing the cursor is only really required when you do not "exhaust" the results. Or in other terms, iterate over all the possible results returned by the cursor. Leaving a "cursor" open is like leaving an open connection that never gets re-used.

Which method returns a cursor in MongoDB?

In MongoDB, the find() method return the cursor, now to access the document we need to iterate the cursor. In the mongo shell, if the cursor is not assigned to a var keyword then the mongo shell automatically iterates the cursor up to 20 documents. MongoDB also allows you to iterate cursor manually.

How can I tell if Pymongo cursor is empty?

Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.


3 Answers

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.

like image 178
brice Avatar answered Sep 21 '22 21:09

brice


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()
like image 30
EwyynTomato Avatar answered Sep 19 '22 21:09

EwyynTomato


You can use cursor.reset();

For PHP : $cursor->reset();

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

like image 28
Irshad Khan Avatar answered Sep 19 '22 21:09

Irshad Khan