Arun Code
Arun Code

Reputation: 1638

Laravel Mongodb groupby

Am trying to pick the last record from the MongoDB using Laravel MongoDB package. I have a many transaction ID in the database in which some are duplicate ID due to some reasons. In that scenario, I need to groupby the transaction id, and sort it according to time and get the last one.

example

transcation_id status timestamps
1              success 
2              success
3              failed
4              success
3              failed
5              success
3              success

So when I am querying I need the transaction_id of 3 as success, which is the last status with the time stamp. However, my query gives me 3 as failed.

$query  = MyCollection::whereIn('app_id' , $appId->toArray())
                ->select(['transcation_id',.....,'created_at'])
                ->orderBy('updated_at')
                ->groupBy('transcation_id')
                ->get();

Please correct me where am doing wrong.

Upvotes: 0

Views: 122

Answers (1)

sandip kakade
sandip kakade

Reputation: 1356

Laravel collections has method last

Model::all() -> last(); // last element 

This is the best way to do it.

For better solutions use this doc

Upvotes: 1

Related Questions