$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[March 01, 2025] MongoDB

MongoDB with Laravel: Getting Started

MongoDB with Laravel: Getting Started

────────────────────────────────────────────────────────

MongoDB with Laravel: Getting Started

Tip: Use the Official Package

composer require mongodb/laravel-mongodb

This is the officially maintained package, not the old jenssegers/mongodb.

Gotcha: Different Model Base Class

use MongoDB\Laravel\Eloquent\Model;

class Post extends Model
{
    protected $connection = 'mongodb';
}

Don't use Illuminate\Database\Eloquent\Model.

Tip: No Migrations Needed

MongoDB is schemaless. Just start creating documents:

Post::create(['title' => 'Hello', 'tags' => ['php', 'mongodb']]);

Gotcha: _id Instead of id

MongoDB uses _id (ObjectId) as the primary key. The package maps it to id in Eloquent, but raw queries use _id.

Tip: Configuration

'mongodb' => [
    'driver' => 'mongodb',
    'dsn' => env('DB_URI', 'mongodb://localhost:27017'),
    'database' => env('DB_DATABASE', 'myapp'),
],

Gotcha: No Joins

MongoDB doesn't support SQL-style joins. Use embedding or manual references.

Tip: Raw Queries

Post::raw(function ($collection) {
    return $collection->find(['tags' => 'php']);
});

Access the native MongoDB collection for advanced queries.

Gotcha: Schema Validation

MongoDB doesn't enforce schema by default. Add validation if needed:

DB::command([
    'collMod' => 'posts',
    'validator' => ['$jsonSchema' => ['required' => ['title']]],
]);

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

Integrating MongoDB with Laravel requires a different mental model. The MongoDB Laravel package (jenssegers/mongodb) provides Eloquent-like syntax, but underneath it uses MongoDB queries that behave very differently from SQL. The biggest surprise for my team was that 'joins' don't exist — you either embed or reference. We had to redesign our schema twice before we internalized this. Start by modeling your access patterns, not your data structure.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts