Programming

How to Use Mongodb With Laravel

We got a project from a retailer whose catalog refused to sit still: every product category had different attributes, plus event logs and content with nested fields. MongoDB was the right fit, and the first hour of setup went the way it usually does: a renamed package, a retired shell command and a Linux package that no longer installs cleanly.

Developer working on how to use MongoDB with Laravel across two monitors.

Here is how to use MongoDB with Laravel the way it works in 2026: the official mongodb/laravel-mongodb package, the PHP mongodb extension, and either MongoDB Atlas or a local server. Every class name and method below matches the package’s 5.12.0 source code, and every PHP snippet passes a syntax check.

Quick answer: To use MongoDB with Laravel, install the mongodb PHP extension, run composer require mongodb/laravel-mongodb, add a mongodb connection with your connection string to config/database.php, and extend MongoDB\Laravel\Eloquent\Model in your models. After that, Eloquent methods like create(), where() and update() work on MongoDB collections, and you can add indexes, embedded documents and transactions as your app grows.

What You Need Before You Start

You need four things: PHP 8.2 or newer, the mongodb PHP extension, a Laravel 12 or 13 app, and a MongoDB database, either a free Atlas cluster or a local server. The current package release, 5.12.0, requires ext-mongodb version 1.21 or 2.x and Laravel’s database component 12.51 or 13.

RequirementWhat the current release needsHow to check
PHP8.2 or newer (Laravel 13 itself needs 8.3)php -v
PHP extensionmongodb 1.21+ or 2.xphp --ri mongodb
Laravel12.51+ or 13php artisan --version
Packagemongodb/laravel-mongodb 5.xcomposer show mongodb/laravel-mongodb
DatabaseMongoDB Atlas or a local mongodmongosh connects

Requirements come from the package’s composer.json at tag 5.12.0 (GitHub) and Laravel’s deployment docs, which list PHP 8.3 as the minimum for Laravel 13 (Laravel docs). If you are new to Laravel, set up a project first with our guide on how to install Laravel, and check your version with our guide to checking your Laravel version.

mongodb/laravel-mongodb vs jenssegers/mongodb

They are the same project. Jens Segers created it as jenssegers/mongodb, and it moved to MongoDB, Inc. under the name mongodb/laravel-mongodb. The new package’s composer.json declares that it replaces jenssegers/mongodb, and the namespace changed from Jenssegers\Mongodb\ to MongoDB\Laravel\.

If older code tells you to extend Jenssegers\Mongodb\Eloquent\Model, that code will not run on a current install. Use MongoDB\Laravel\Eloquent\Model instead.

What About Laravel 10 or 11?

MongoDB’s upgrade guide says that starting in version 5.9, the minimum Laravel version is 12.0 and the minimum PHP version is 8.2 (MongoDB docs). An older Laravel app needs an older package release. Check MongoDB’s compatibility table before you pin a version, or plan the Laravel upgrade first.

Step 1: Install the MongoDB PHP Extension

The mongodb PHP extension is the low-level driver that talks to the database. Laravel’s package will not install without it. PHP’s manual now recommends PIE, the PHP Installer for Extensions, and lists PECL as deprecated (PHP manual).

On macOS or Linux, install it with PIE or PECL:

# Recommended
pie install mongodb/mongodb-extension

# Older method
sudo pecl install mongodb

Then enable it in your php.ini file:

extension=mongodb.so

On Windows, download the php_mongodb.dll build from the extension’s GitHub releases that matches your PHP version, thread safety (TS or NTS) and architecture. Copy it to PHP’s ext folder and add extension=php_mongodb.dll to php.ini.

Confirm it loaded:

php --ri mongodb

If that prints the extension version, you are ready. If it says the extension is not present, run php --ini to find which php.ini your command line uses. Your web server may use a different one.

Step 2: Choose MongoDB Atlas or a Local Server

For most projects, start with MongoDB Atlas, the managed cloud service. Its free M0 tier costs $0, includes 512 MB of storage and handles up to 100 operations per second, which is plenty for learning and small prototypes (MongoDB pricing).

To get a connection string in Atlas, create a free cluster and a database user, then go to Clusters, click Connect, choose Drivers, select PHP and copy the string. It looks like mongodb+srv://user:password@cluster0.example.mongodb.net/. Add your current IP address to the Atlas network access list, or the connection will time out.

Running MongoDB Locally on Ubuntu

For a local server on Ubuntu, install the official mongodb-org package from MongoDB’s repository. MongoDB’s install guide warns that the mongodb package in Ubuntu’s own repository is not maintained by MongoDB and conflicts with mongodb-org. MongoDB 8.0 supports Ubuntu 24.04, 22.04 and 20.04 LTS on x86_64 (MongoDB docs).

sudo systemctl start mongod
mongosh

The old mongo shell has been replaced by mongosh. On macOS, Homebrew works through the mongodb/brew tap. On Windows, use the MSI installer from MongoDB’s download center.

MongoDB Compass

Compass is MongoDB’s free desktop GUI. Paste the same connection string you put in Laravel, and you can browse collections, check the documents your models create, run aggregation pipelines and see which indexes exist. It is the fastest way to confirm your Laravel code wrote what you expected.

Step 3: Install the Laravel MongoDB Package

Install the official package with Composer. Its service providers register automatically through Laravel’s package discovery, so a new Laravel 12 or 13 app needs no manual provider entry.

composer require mongodb/laravel-mongodb:^5.12

The package’s composer.json lists MongoDB\Laravel\MongoDBServiceProvider and MongoDB\Laravel\MongoDBBusServiceProvider for auto-discovery. If your app disables package discovery, add the main provider to bootstrap/providers.php yourself. Composer setup problems are covered in our guide to installing Composer for Laravel.

If Composer stops with an error saying the package requires ext-mongodb and it is missing from your system, the extension from Step 1 is not loaded for the PHP version Composer uses.

Step 4: Configure the MongoDB Connection

Add a mongodb connection to config/database.php, put the connection string in .env, and set it as the default connection if MongoDB is your main database. If you also use MySQL or PostgreSQL, leave the default alone and point individual models at mongodb.

In .env:

DB_CONNECTION=mongodb
DB_URI="mongodb+srv://appUser:yourPassword@cluster0.example.mongodb.net/"
DB_DATABASE=webzeto_app

In config/database.php, inside the connections array:

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

This matches the connection format in MongoDB’s Laravel docs, where dsn holds the connection string and database names the database (MongoDB docs). With the mongodb+srv:// format, leave out the port number. MongoDB’s quick start also warns that variables set in your shell override .env, which explains many “it connects in Tinker but not in the browser” bugs.

Run php artisan config:clear after any change if you cached your config.

Step 5: Create a MongoDB Eloquent Model

A MongoDB model extends MongoDB\Laravel\Eloquent\Model instead of Laravel’s base model. Set the connection, the collection name through $table, and the fields you allow for mass assignment. Everything else, including casts and accessors, works like normal Eloquent.

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

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

    protected $table = 'posts';

    protected $fillable = [
        'title',
        'slug',
        'status',
        'tags',
        'author',
        'views',
        'published_at',
    ];

    protected function casts(): array
    {
        return [
            'tags' => 'array',
            'views' => 'integer',
            'published_at' => 'datetime',
        ];
    }
}

Two version 5 changes trip people up. The $collection property was removed, so use $table. And id is now an alias for MongoDB’s _id field, so a document can’t hold separate id and _id values (MongoDB docs). In practice, $post->id returns the document’s ObjectId as a string.

CRUD Operations With MongoDB in Laravel

Create, read, update and delete work through the same Eloquent methods you use with MySQL. The difference is that MongoDB documents can hold nested objects and arrays, and the package adds methods such as push() and pull() to change arrays without rewriting the whole document.

Create Documents

use App\Models\Post;

$post = Post::create([
    'title' => 'How to Use MongoDB With Laravel',
    'slug' => 'mongodb-laravel',
    'status' => 'published',
    'tags' => ['laravel', 'mongodb'],
    'author' => ['name' => 'Ayesha', 'role' => 'editor'],
    'views' => 0,
    'published_at' => now(),
]);

The author field is stored as an embedded object, not a separate table.

Read and Filter Documents

// Find by id (the ObjectId string)
$post = Post::find($id);

// Filter on a nested field with dot notation
$editorPosts = Post::where('author.role', 'editor')
    ->where('status', 'published')
    ->orderBy('published_at', 'desc')
    ->take(10)
    ->get();

// Match a value inside an array field
$laravelPosts = Post::where('tags', 'laravel')->get();

Update Documents and Arrays

// Update fields on matching documents
Post::where('slug', 'mongodb-laravel')->update(['status' => 'archived']);

// Increment a counter
Post::where('slug', 'mongodb-laravel')->increment('views');

// Add a tag only if it is not already there ($addToSet)
$post->push('tags', 'eloquent', true);

// Remove a tag ($pull)
$post->pull('tags', 'mongodb');

The third argument to push() switches from MongoDB’s $push operator to $addToSet, which skips duplicates. We checked this in the package source.

Delete Documents

$post->delete();

Post::where('status', 'archived')->delete();

For soft deletes, use the package’s own trait, MongoDB\Laravel\Eloquent\SoftDeletes, in your model.

Relationships: Embedded Documents vs References

MongoDB gives you two ways to relate data. Embed child data inside the parent document when you always read them together, such as comments on a post. Store a reference, an id pointing to another collection, when the related data is large, shared or updated on its own, such as users.

Embedded Documents With embedsMany

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;
use MongoDB\Laravel\Relations\EmbedsMany;

class Article extends Model
{
    protected $connection = 'mongodb';

    public function comments(): EmbedsMany
    {
        return $this->embedsMany(Comment::class);
    }
}
$article->comments()->save(new Comment(['body' => 'Great guide']));

foreach ($article->comments as $comment) {
    echo $comment->body;
}

Embedded comments are stored inside the article document, so loading an article loads its comments in one read. The trade-off: a single document has a 16 MB size limit in MongoDB, so don’t embed lists that can grow without end.

References With hasMany and belongsTo

Standard hasMany, belongsTo and belongsToMany relations work between MongoDB models. To relate a MySQL model to a MongoDB model, add the MongoDB\Laravel\Eloquent\HybridRelations trait to the SQL-side model.

Indexes and Migrations for MongoDB

MongoDB creates collections on the first insert, so you don’t need migrations to create tables. You still need migrations for indexes, because an unindexed query scans every document. The package’s schema builder adds index(), unique(), sparse(), expire() and geospatial() on collections.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use MongoDB\Laravel\Schema\Blueprint;

return new class extends Migration
{
    protected $connection = 'mongodb';

    public function up(): void
    {
        Schema::create('posts', function (Blueprint $collection) {
            $collection->unique('slug');
            $collection->index('status');
            $collection->index('author.role');
        });

        Schema::create('login_attempts', function (Blueprint $collection) {
            // Delete each document 1 hour after its created_at time
            $collection->expire('created_at', 3600);
        });
    }

    public function down(): void
    {
        Schema::drop('posts');
        Schema::drop('login_attempts');
    }
};

Run it with php artisan migrate. The expire() call creates a TTL index, which tells MongoDB to delete old documents for you. It is a clean fit for logs, OTP codes and rate-limit records. Check the result in Compass under the collection’s Indexes tab.

Aggregations and Raw MongoDB Queries

For reports, use MongoDB’s aggregation pipeline through raw(). It gives you the underlying MongoDB\Collection, so you can call any method from the official PHP library while staying inside Laravel.

use Illuminate\Support\Facades\DB;
use MongoDB\Collection;

$postsPerAuthor = DB::connection('mongodb')
    ->table('posts')
    ->raw(fn (Collection $collection) => $collection->aggregate([
        ['$match' => ['status' => 'published']],
        ['$group' => ['_id' => '$author.name', 'total' => ['$sum' => 1]]],
        ['$sort' => ['total' => -1]],
    ]))
    ->toArray();

When you call raw() on an Eloquent model instead of DB::table(), the package turns cursor results into model instances. For grouped results that aren’t real documents, the query builder version above is cleaner.

Authentication, Queues, Cache and Sessions on MongoDB

The package can run most of Laravel’s database-backed features on MongoDB. Its service provider registers a mongodb driver for the database, sessions, cache and queues, plus a GridFS filesystem driver for file storage.

For login, make your User model extend the package’s user class (MongoDB docs):

<?php

namespace App\Models;

use MongoDB\Laravel\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $connection = 'mongodb';

    protected $table = 'users';

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];
}

To store cache or sessions in MongoDB, set the driver to mongodb in config/cache.php or config/session.php. For Laravel Sanctum tokens, MongoDB’s docs show a custom PersonalAccessToken model that uses the MongoDB\Laravel\Eloquent\DocumentModel trait.

Transactions and Testing With MongoDB

MongoDB transactions need a replica set or sharded cluster. A standalone local mongod doesn’t support them. Atlas clusters, including the free tier, run as replica sets, so DB::transaction() works there out of the box.

use App\Models\Account;
use Illuminate\Support\Facades\DB;

DB::connection('mongodb')->transaction(function () {
    $sender = Account::where('number', 223344)->first();
    $sender->decrement('balance', 200);

    $receiver = Account::where('number', 776655)->first();
    $receiver->increment('balance', 200);
}, attempts: 3);

MongoDB’s transactions page lists three limits: no nested transactions, no parallel operations inside one transaction, and no support for Laravel’s RefreshDatabase or DatabaseTransactions testing traits (MongoDB docs). In tests, use the DatabaseMigrations trait instead, and point the test environment at a separate database name.

Common Laravel MongoDB Errors and Fixes

Most setup errors come from the PHP extension, old namespaces or the connection string. Match the message you see to the fix below.

Error or symptomCauseFix
Class "MongoDB\Driver\Manager" not foundThe mongodb extension isn’t loadedInstall it and enable it in the php.ini your web server uses
Composer says ext-mongodb is missingComposer runs on a PHP build without the extensionRun php --ri mongodb with the same PHP binary Composer uses
Class "Jenssegers\Mongodb\Eloquent\Model" not foundOld namespace from pre-v4 codeChange to MongoDB\Laravel\Eloquent\Model
Connection timeout to AtlasYour IP isn’t on the Atlas access listAdd your IP or your server’s IP in Atlas network access
.env changes ignoredCached config or a shell variable overrides .envRun php artisan config:clear and unset the shell variable
Transaction error on a local serverStandalone mongod has no transaction supportUse Atlas or run a single-node replica set locally
id and _id behave oddly after upgradingVersion 5 makes id an alias of _idRemove separate id fields from documents
sudo apt install mongodb fails or installs an old versionThat Ubuntu package isn’t maintained by MongoDBInstall mongodb-org from MongoDB’s repository

When MongoDB Is the Wrong Choice for Laravel

MongoDB is not a drop-in upgrade from MySQL. If your data is highly relational, such as orders, invoices and inventory with strict joins and reporting, a SQL database is usually simpler and safer. Laravel’s ecosystem also assumes SQL in many packages.

MongoDB earns its place when documents vary in shape, when you store nested data you read as one unit, or when you need features such as TTL indexes, geospatial queries or Atlas Search. Many of our client apps run both: MySQL for orders and billing, MongoDB for catalogs, logs or activity feeds. The HybridRelations trait exists for exactly that setup.

If you’d rather have an experienced team plan the data model, our Laravel development service builds and reviews Laravel apps on MySQL, MongoDB or both. For a faster local workflow while you build, see how to use Laravel Debugbar to inspect queries, and our guide to deploying a Laravel project on cPanel when you go live.

FAQ

Short answers to the questions developers ask most about MongoDB and Laravel.

How do I use MongoDB with Laravel as a beginner?

Start with a free MongoDB Atlas cluster so you don’t have to install a database server. Install the mongodb PHP extension, run composer require mongodb/laravel-mongodb, paste your Atlas connection string into .env, and make one model extend MongoDB\Laravel\Eloquent\Model. Then use normal Eloquent methods.

What is mongodb/laravel-mongodb?

It is the official Laravel integration for MongoDB, maintained by MongoDB, Inc. It adds a mongodb database driver, an Eloquent model class, a query builder, a schema builder for indexes, and drivers for cache, sessions, queues and GridFS file storage.

Is jenssegers/mongodb the same as mongodb/laravel-mongodb?

Yes. The package was renamed when ownership moved to MongoDB, Inc. The new package replaces jenssegers/mongodb, and the namespace changed from Jenssegers\Mongodb\ to MongoDB\Laravel\. New projects should require mongodb/laravel-mongodb.

Can I use jenssegers/mongodb with Laravel 10?

Current releases of mongodb/laravel-mongodb need Laravel 12 or 13, since version 5.9 raised the minimum to Laravel 12. A Laravel 10 app needs an older package release. Check MongoDB’s compatibility table, or upgrade Laravel before adding MongoDB.

Where is the Laravel MongoDB package on Packagist?

It is listed on Packagist as mongodb/laravel-mongodb, and Composer installs it with composer require mongodb/laravel-mongodb. The source code and release tags live on GitHub under the mongodb organization.

Do I need the MongoDB PHP extension for Laravel?

Yes. The package depends on the mongodb PHP extension, version 1.21 or 2.x for the current release. Install it with PIE or PECL on macOS and Linux, or a DLL on Windows, then enable it in php.ini and check it with php --ri mongodb.

Can I use MongoDB Atlas with Laravel?

Yes, and it is the easiest option. Copy the mongodb+srv:// connection string from Atlas into DB_URI in .env, add your IP to the Atlas access list, and Laravel connects. The free M0 tier includes 512 MB of storage.

What is MongoDB Compass used for with Laravel?

Compass is MongoDB’s free desktop GUI. Connect it with the same connection string Laravel uses to browse collections, check the documents your models create, test queries and aggregation pipelines, and confirm that your migration indexes exist.

Does Laravel’s migrate command work with MongoDB?

Yes. You don’t need migrations to create collections, because MongoDB creates them on first insert, but you should use migrations to create indexes. Use MongoDB\Laravel\Schema\Blueprint with methods such as unique(), index() and expire(), then run php artisan migrate.

Conclusion

Back to those projects where the data refuses to sit still. Once you know how to use MongoDB with Laravel the current way, the setup takes minutes: the mongodb PHP extension, the official mongodb/laravel-mongodb package, one connection in config/database.php, and models that extend MongoDB\Laravel\Eloquent\Model.

From there, the real work is design. Embed what you read together, reference what grows or changes alone, index every field you filter on, and keep transactions for cases that truly need them. If your data is heavily relational, keep it in SQL and let MongoDB handle the flexible parts.

Which part of your current Laravel app would gain the most from a flexible document model: the catalog, the logs, or the user activity feed?

Leave a Reply

Your email address will not be published. Required fields are marked *

Share the article

Written By

Author Avatar

October 28, 2026

Hi there! I’m Ayesha Khan, a skilled content writer with a strong background in computer science. I specialize in transforming complex ideas into clear, engaging, and easy-to-understand content. With 10 years of experience working across different industries, I focus on delivering content that not only informs but also connects with readers. I’m passionate about writing and take pride in creating high-quality work that helps clients communicate their message effectively.