How to set limit() into MongoQuery Using PHP?

Balakumar B picture Balakumar B · Jan 2, 2017 · Viewed 8.3k times · Source

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?

Answer

Eborbob picture Eborbob · Jan 31, 2018

The new PHP MongoDB library doesn't have the limit() and sort() methods on the cursors like the old PHP Mongo library had. These must now be specified at query time, e.g.:

$collection->find($query, [
    'limit' => 10,
    'sort'  => [ 'date' => -1 ],
    'projection' => [
        '_id' => 1,
        'description' => 1,
    ]
];