I have just started using mongoDb as my backend for PHP.
I am simply using find() query for one of my needs. I want only first 100 results but also want to get total available results. I am trying this.
$cursor = $this->dbReference->dbName->find($query);
if($count != 0)
{
$cursor->skip($startIndex);
$cursor->limit($count);
}
$totalCount = $cursor->count();
$entries = array();
while ($cursor->hasNext())
{
$cursor->next();
$entry = $cursor->current();
array_push($entries , $entry);
}
Now The problem is.. T his search result contains exactly more than 50K results. But I am retrieving only 100 at a time. I am using $cursor->count() for getting total number of available result rows. on this line error is showing that "Cursor timed out". Please can anyone suggest me whats the problem? or what is the alternative to find total count of search result.
Thanks in advance.
collection. find () function is used to search for documents in the collection, the result returns a pointer to the collection of documents returned which is called a cursor. By default, the cursor will be iterated automatically when the result of the query is returned.
Cursors are automatically closed by the mongo server when they're inactive for more than 10 minutes, or if the client has exhausted the cursor. The MongoDB docs recommend either closing cursors, or ensuring they're exhausted by the client.
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.
It is however very inefficient to retrieve documents one at a time from the server. Batch size is how many documents the driver requests from the server at once.
You can solve cursor time out problem by adding this code before find()
:
MongoCursor::$timeout = -1;
$cursor = $this->dbReference->dbName->find($query);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With