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?
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,
]
];
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]);
If you are using MongoDB driver with the MongoDB PHP library, then
require 'vendor/autoload.php';
$client = new MongoDB\Client("mongodb://localhost:27017");
//SELECT * FROM YOUR_TABLE_NAME LIMIT 10
//db.YOUR_COLLECTION_NAME.find({}).limit(10);
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array(),array('limit'=>10));