MongoDb/php Get max id value on a collection

5.6k Views Asked by At

I want to get the max id value on a collection.

How do I convert the mongoDb query:

db.tweets.find({},{id:1}).sort({id:-1}).limit(1)

to Mongo Query Language Statement using PHP?

I'm trying

$db->tweets->find(
    array(),
    array("id"=>1)
)->sort(array("id"=> -1))->limit(1);

but that doesn't work.

1

There are 1 best solutions below

1
On

I checked this and it works for me:

$val = $db->myCollection->find(array(), array('_id' => 1))->sort(array('_id' => -1))->limit(1);

The error in your code is that it should be "_id" and not "id". Also, I hope $db->tweets is a MongoCollection object and you have ensured this. Hope this helps.