Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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,
    ]
];
over 4 years ago · Santiago Trujillo Report

0

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]);
over 4 years ago · Santiago Trujillo Report

0

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));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!