How to set limit() into MongoQuery Using PHP?

12k views Asked by At

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?

4

There are 4 answers

1
Yury Fedorov On BEST ANSWER

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]);
0
Scott Fleming On

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

...

0
Nanhe Kumar On

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));
0
Eborbob On

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,
    ]
];