Reputation: 800
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?
Upvotes: 4
Views: 12543
Reputation: 451
This is a working solution for the new PHP mongo. It displays the top played songs in my collection by num_plays
values in each record.
$collection = (new MongoDB\Client)->scottybox->pianobar;
// display top 25 played titles/artist sorted by num_plays
$filter = [];
$result = $collection->find($filter,
[ 'limit' => 25,
'sort' => [ 'num_plays' => -1 ],
'projection' => [
'num_plays' => 1,
'artist' => 1,
'title' => 1
]]
);
echo "<h2>Top 25 Played Songs</h2>";
foreach($result as $row){
echo $row->artist . " - " . $row->title . ": ";
echo $row->num_plays . "<br/>";
}
Top 25 Played Songs
Led Zeppelin - Stairway To Heaven: 65
The Rolling Stones - Gimme Shelter: 36
Tom Petty - Mary Jane's Last Dance: 34
Led Zeppelin - Whole Lotta Love: 29
The Rolling Stones - (I Can't Get No) Satisfaction: 28
Scorpions - Rock You Like A Hurricane: 28
Led Zeppelin - Hey Hey What Can I Do: 28
...
Upvotes: 0
Reputation: 16307
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));
Upvotes: 2
Reputation: 1975
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,
]
];
Upvotes: 9
Reputation: 14938
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]);
Upvotes: 5