Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 754
Balakumar B Avatar asked Oct 17 '25 18:10

Balakumar B


1 Answers

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,
    ]
];
like image 89
Eborbob Avatar answered Oct 20 '25 09:10

Eborbob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!