Skip to main content

Introduction

MongoDB is one of the most popular NoSQL document-oriented databases. It features high write performance (ideal for analytics and IoT), high availability (automatic failover with replica sets), horizontal scalability (sharding), and a powerful query language (aggregation, full-text search, geospatial queries). Unlike SQL databases’ row and column format, each record in MongoDB is a document in BSON (Binary JSON) format. Your application retrieves this data in JSON format.
When using MongoDB with Laravel, it is recommended to use the mongodb/laravel-mongodb package, which is maintained by MongoDB. This package provides rich integration with Eloquent and various Laravel features.

Installation

MongoDB PHP Driver

The mongodb PHP extension is required to connect to MongoDB. If you’re using Laravel Herd or php.new, it’s already installed. To install manually, use PECL:
pecl install mongodb
For detailed installation instructions, see the MongoDB PHP Driver Installation Guide.
Ensure the mongodb PHP extension is enabled in both your CLI and web server configurations, as they may differ.

Starting MongoDB Server

MongoDB Community Server can be used for local development. For installation instructions on Windows, macOS, Linux, and Docker, see the official installation guide. Using Docker:
# docker-compose.yml
services:
  mongodb:
    image: mongo:8
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: laravel_app
    volumes:
      - mongodb_data:/data/db

volumes:
  mongodb_data:
docker compose up -d
For cloud hosting, MongoDB Atlas is available. To access an Atlas cluster locally, you need to add your IP address to the project’s IP access list.

Installing the laravel-mongodb Package

Install the mongodb/laravel-mongodb package using Composer:
composer require mongodb/laravel-mongodb

Configuration

Environment Variables

Add MongoDB connection information to your .env file:
MONGODB_URI="mongodb://localhost:27017"
MONGODB_DATABASE="laravel_app"
If using MongoDB Atlas, change the connection string to your Atlas connection string:
MONGODB_URI="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority"
MONGODB_DATABASE="laravel_app"

config/database.php

Add a mongodb connection to the connections array in config/database.php:
'connections' => [

    // ... existing connections ...

    'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('MONGODB_URI', 'mongodb://localhost:27017'),
        'database' => env('MONGODB_DATABASE', 'laravel_app'),
    ],

],
If you’re using both relational databases like MySQL and MongoDB simultaneously, simply keep the default connection unchanged and add the mongodb connection. You can switch connections per model.

Key Features

Eloquent Models

By extending MongoDB\Laravel\Eloquent\Model, you can work with MongoDB using almost the same API as standard Eloquent models:
<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class Article extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'articles'; // Collection name (auto-generated from class name if omitted)

    protected $fillable = [
        'title',
        'body',
        'tags',
        'published_at',
    ];
}
MongoDB is schema-less, so migrations are not required. Collections are created automatically when you save documents.

Basic CRUD Operations

You can use the same API as standard Eloquent:
use App\Models\Article;

// Create
$article = Article::create([
    'title' => 'Getting Started with MongoDB',
    'body' => 'MongoDB is a document-oriented database.',
    'tags' => ['nosql', 'mongodb', 'laravel'],
    'published_at' => now(),
]);

// Read
$article = Article::find('64f1a2b3c4d5e6f7a8b9c0d1');
$articles = Article::where('tags', 'nosql')->get();

// Update
$article->update(['title' => 'Revised: Getting Started with MongoDB']);

// Delete
$article->delete();

Arrays and Embedded Documents

You can work directly with MongoDB’s arrays and embedded documents:
// Push to array field
$article->push('tags', 'database');

// Pull from array field
$article->pull('tags', 'nosql');

// Query embedded documents
$articles = Article::where('meta.author', 'Taylor')->get();

Query Builder

Use MongoDB’s query builder to write complex queries. For details, see the laravel-mongodb Query Builder documentation:
use Illuminate\Support\Facades\DB;

// Basic queries
$articles = DB::connection('mongodb')
    ->collection('articles')
    ->where('tags', 'laravel')
    ->orderBy('published_at', 'desc')
    ->limit(10)
    ->get();

// Aggregation pipeline
$stats = DB::connection('mongodb')
    ->collection('orders')
    ->raw(function ($collection) {
        return $collection->aggregate([
            ['$group' => ['_id' => '$status', 'total' => ['$sum' => '$amount']]],
            ['$sort' => ['total' => -1]],
        ]);
    });

Cache Driver

MongoDB’s cache driver uses TTL indexes to automatically delete expired entries. For details, see the Cache Driver documentation. Add a store to config/cache.php:
'stores' => [

    'mongodb' => [
        'driver' => 'mongodb',
        'connection' => 'mongodb',
        'collection' => 'cache',
    ],

],
Change the cache driver to MongoDB in .env:
CACHE_STORE=mongodb

Queue Driver

You can use MongoDB as a queue driver. For details, see the Queue Driver documentation: Add a connection to config/queue.php:
'connections' => [

    'mongodb' => [
        'driver' => 'mongodb',
        'connection' => 'mongodb',
        'collection' => 'jobs',
        'queue' => env('MONGODB_QUEUE', 'default'),
        'retry_after' => (int) env('MONGODB_QUEUE_RETRY_AFTER', 90),
        'after_commit' => false,
    ],

],
Change the queue connection to MongoDB in .env:
QUEUE_CONNECTION=mongodb

File Storage with GridFS

Store files using MongoDB’s GridFS. Use the Flysystem GridFS adapter. For details, see the GridFS documentation:
composer require league/flysystem-gridfs
Add a disk to config/filesystems.php:
'disks' => [

    'gridfs' => [
        'driver' => 'gridfs',
        'connection' => 'mongodb',
        'database' => env('MONGODB_DATABASE', 'laravel_app'),
    ],

],
use Illuminate\Support\Facades\Storage;

// Upload file
Storage::disk('gridfs')->put('file.pdf', $contents);

// Retrieve file
$contents = Storage::disk('gridfs')->get('file.pdf');

Using MySQL and MongoDB Together

Laravel allows you to use MySQL and MongoDB simultaneously. Specify the connection per model using the $connection property:
// Standard Eloquent model using MySQL
class User extends \Illuminate\Database\Eloquent\Model
{
    protected $connection = 'mysql';
}

// Model using MongoDB
class Article extends \MongoDB\Laravel\Eloquent\Model
{
    protected $connection = 'mongodb';
}
For relationships between MySQL and MongoDB models, see the Hybrid Relationships documentation.

Summary

  1. Install PHP extension with pecl install mongodb
  2. Start MongoDB server (locally, Docker, or Atlas)
  3. Install package with composer require mongodb/laravel-mongodb
  4. Set MONGODB_URI and MONGODB_DATABASE in .env
  5. Add mongodb connection to config/database.php
CharacteristicMongoDBMySQL
Data ModelDocuments (JSON/BSON)Tables (rows/columns)
SchemaSchema-less (flexible)Fixed schema
ScalingHorizontal scaling (easy)Vertical scaling (primary)
TransactionsMulti-document support (v4+)Full ACID support
Best ForLogs, analytics, IoT, flexible structuresStructured data, complex relations
FeatureConfiguration
Eloquent ModelsExtend MongoDB\Laravel\Eloquent\Model
Query BuilderDB::connection('mongodb')->collection(...)
Cacheconfig/cache.php + CACHE_STORE=mongodb
Queuesconfig/queue.php + QUEUE_CONNECTION=mongodb
File Storageconfig/filesystems.php + GridFS adapter

Next Steps

laravel-mongodb Official Docs

Full reference for Eloquent, query builder, relationships, and all features

Quick Start

Learn the basics of MongoDB and Laravel quickly

Database Configuration

Laravel database connection configuration basics

Eloquent Introduction

Introduction to Eloquent ORM basics
Last modified on June 9, 2026