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

后端 未结 1 1170
时光取名叫无心
时光取名叫无心 2021-01-11 14:43

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?

1条回答
  •  臣服心动
    2021-01-11 15:24

    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:

    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.

    0 讨论(0)
提交回复
热议问题