Random Record from MongoDB using Laravel Query Builder

Here’s a quick snippet that’s been working well enough for me on a project I’m putting together.  I based it off a suggestion from a Stack Overflow thread.

For starters, let me preface this that I’m using Laravel v4.2. As of this moment, either v5.0 isn’t ready enough for me or I’m not ready for it. v4.2 is perfectly fine and when I need to upgrade, I will.  It also depends on the Laravel MongoDB database implementation that can be loaded through Composer or otherwise.

I personally prefer the DB facade that aliases the Illuminate\Database\DatabaseManager for accessing my databases.  I find the Eloquent model approach limiting and find myself bending my code and approach to use it.  Just my opinion.  Just such a situation is pulling random records.  Adjusting the SO suggestion to the available fluent methods, I cobbled together this.

$rand = rand(0, DB::collection($collectionName)->count() - 1);
DB::collection($collectionName)->limit(-1)->skip($rand)->first();

I’ll admit I don’t know much of the internals but the results are current working for me.

Leave a Reply