php: cursor rewind query

62 views
Skip to first unread message

Ananth Deodhar

unread,
Jul 14, 2009, 12:21:23 AM7/14/09
to mongod...@googlegroups.com
Hi,

Could someone explain to me how the cursor rewind works? If I am using 4-5 cursor's (one per collection) in a script, what happens internally? I read somewhere on the site that the cursor is the only object which isn't stateless. 

When I do a find().limit(5) on a collection and then a rewind() it returns only 4 results instead of the usual 5. In what cases would I need to use rewind()?

Thanks.
 
- Ananth
 

Kristina Chodorow

unread,
Jul 14, 2009, 9:58:44 AM7/14/09
to mongod...@googlegroups.com
Probably what you want is reset(), which sets up the cursor to re-query the database next time you try to get a document. 

rewind() re-queries the database and then gets the first document and makes it accessible through current().  In PHP, it is mostly just used internally for foreach loops. 

I'd imagine the reason you're getting 4 results when you expect 5 is that you are using getNext(), whereas you have to call current() after using rewind() to get the first result.  So your code needs to do something like:

$cursor->rewind();
$obj = $cursor->current(); 
$cursor->next();
$obj2 = $cursor->current(); 
etc.

The following is equivalent but uses reset():

$cursor->reset();
$obj = $cursor->getNext();
$obj2 = $cursor->getNext();

"getNext()" is equivalent to "next(); current();"
Reply all
Reply to author
Forward
0 new messages