Search code examples
phpmongodbfindlimit

MongoDB PHP Limit not working


I use this code in the MongoDB PHP driver to get all documents in the database

$result = $collection->find();

foreach ($result as $doc) {
    print_r($doc);
}

However, when adding a limit to it, it doesn't work anymore: no documents get printed anymore:

$result = $collection->find()->limit(10);

foreach ($result as $doc) {
    print_r($doc);
}

There are certainly enough documents in the database. I cannot figure out what the problem with this is.


Solution

  • I have fixed the problem by taking a look at the source of the beta version. The documentation only appeared to be for the legacy mongo extension and not the newer mongodb extension.

    The error logs showed this: Call to undefined method MongoDB\\Driver\\Cursor::addOption(). I checked out the documentation and concluded the function should have worked because it said (PECL mongo >=0.9.0). Note the missing db after mongo.

    I fixed it by doing: $collection->find([], [ 'limit' => 2 ]);, providing an empty filters array and adding my options in another array afterwards.