Search code examples
phpmongodblaravelmongodb-querylaravel-5.3

Selecting the latest record by runing laravel raw mongodb query


I'm trying ti get the latest inserted record of mongodb as a collection in laravel using moloquent (jessenger/mongodb) package.

But I can not figure out how to run this raw query in laravel :

db.collection.find().limit(1).sort({$natural:-1})

I know the formate of raw query in laravel is :

$bcamps = Bcamp::raw()->find(my raw query);

But how can I return the last inserted record as a collection by running that raw query in laravel 5.3 ?


Solution

  • I've figured how to do that by selecting the last record and then get it as a collection to be able to update it.

    $bcamps = Bcamp::raw()->findOne([],['sort' => ['_id' => -1],'projection' => ['_id' => 1]]);
    
    $bcamps = Bcamp::where('_id', '=' , $bcamps->_id)->first();
    

    Hope to save some other people time.