Search code examples
phpmongodbphp-mongodb

How to set limit() into MongoQuery Using PHP?


I have to use Mongodb with php, and tried to get data from mongocollection using php. the follwing mongoquery with php return record successfully. but i want to set limit for following query.

PHP Code:

$query = array("\$and"=>array(array('fld'=> array("\$in"=> array('4', '14', '20'))), array('stat'=>array("\$eq"=>"A"))));

$cursor = $this->collection->find($query);

i have also tried follwing way

$query = array("\$and"=>array(array('fld'=> array("\$in"=> array('4', '14', '20'))), array('stat'=>array("\$eq"=>"A")))).limit(2);

But I got Fatal Error

Call to undefined function limit()

How to use limit() in above query?


Solution

  • In PHP, limit() is a method of MongoCursor class, and not of an array. You need to get a cursor first, and then call its limit() method:

    $collection->find($query)->limit(2);
    

    You can also add options array to your find() call with limit parameter:

    $collection->find($query, ['limit' => 2]);