Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Why should I use a cursor instead of iterator_to_array (in PHP)

The PHP documentation for the mongo class says using a cursor instead of iterator_to_array is superior.

Why? What benefits/flexibility will I get from that?

like image 653
CamelCamelCamel Avatar asked Feb 20 '11 23:02

CamelCamelCamel


People also ask

Why cursor is used in MongoDB?

In MongoDB, when the find() method is used to find the documents present in the given collection, then this method returned a pointer which will points to the documents of the collection, now this pointer is known as cursor.

Do I need to close MongoDB cursor?

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.


1 Answers

Using iterator_to_array() makes your driver load all of the results into memory at once, and you could easily run out of memory. This would not be the case with a cursor, which uses lazy-loading!

Straight from the linked docs:

<?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

?>

...

Suppose that, in the example above, $collection was a 50GB collection. We certainly wouldn't want to load that into memory all at once, which is what a cursor is for: allowing the client to access the collection in dribs and drabs.

like image 138
CamilleLDN Avatar answered Oct 19 '22 16:10

CamilleLDN