Getting Started with MongoDB in Laravel 12: A Complete Beginner’s Guide

Author

Kritim Yantra

Jul 12, 2025

Getting Started with MongoDB in Laravel 12: A Complete Beginner’s Guide

🧲 Imagine This…

You're building an app. Your users can create profiles, post comments, upload photos, and maybe even store settings or preferences that vary from user to user. Suddenly, you're dealing with complex data that doesn’t fit neatly into tables. Fields vary. Relationships nest. Migrations multiply.

Traditional SQL databases start to feel like trying to write a novel on a typewriter.

What if you could store and retrieve flexible, evolving data models with ease?

That’s where MongoDB shines.

And the best part? You don’t need to ditch Laravel. With Laravel 12’s MongoDB support, you can use Eloquent, Query Builder, and even queues and caching—without sacrificing performance or developer happiness.

Let’s dive in. 🌊


🧰 What Is MongoDB (in Simple Terms)?

MongoDB is a NoSQL database that stores data in JSON-like documents. That means:

  • No predefined schemas (you don’t need to define every column)
  • You can store arrays, nested documents, and complex types
  • You can retrieve and update just as flexibly

In contrast to SQL databases (like MySQL), MongoDB is optimized for scalability, real-time applications, and schema-less data.

🧠 Think of MongoDB as a big, flexible filing cabinet of documents. Need to add a new field? Just write it in. No migrations, no table rewrites.


📦 Why Use MongoDB with Laravel?

Laravel traditionally works with SQL databases, but modern apps need flexibility. MongoDB offers:

Schema-less design: Perfect for evolving projects
Document embedding: Nest related data instead of joining tables
High scalability: Great for IoT, analytics, logs, etc.
Built-in support for queues, caching, sessions using MongoDB TTL indexes
GridFS: Store and retrieve large files like videos, PDFs, and images

And with the official MongoDB Laravel package, you don’t need to learn a new framework. You just extend what you already know.


🧪 Step 1: Prerequisites

Before we dive in, make sure you have:

  • Laravel 12 installed
  • PHP >= 8.1
  • Composer
  • MongoDB installed locally or a MongoDB Atlas account

🧩 Installing MongoDB PHP Extension

pecl install mongodb

Then add this to your php.ini:

extension=mongodb.so

Verify it’s installed:

php -m | grep mongodb

📝 Tip: You must install it for both CLI and web server (FPM or Apache).


🚀 Step 2: Installing the MongoDB Laravel Package

In your Laravel project root, run:

composer require mongodb/laravel-mongodb

This package integrates MongoDB into Laravel’s Eloquent ORM and query builder.


️ Step 3: Configuration

.env Setup

MONGODB_URI=mongodb://localhost:27017
MONGODB_DATABASE=my_laravel_app

For MongoDB Atlas:

MONGODB_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/my_laravel_app
MONGODB_DATABASE=my_laravel_app

config/database.php

Add a new connection:

'mongodb' => [
    'driver'   => 'mongodb',
    'dsn'      => env('MONGODB_URI'),
    'database' => env('MONGODB_DATABASE'),
],

Set it as default (optional):

DB_CONNECTION=mongodb

🧱 Step 4: Creating Your First MongoDB Model

use MongoDB\Laravel\Eloquent\Model;

class Post extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'posts';
    protected $fillable = ['title', 'content', 'tags'];
}

📝 The collection name is the MongoDB equivalent of a table.


🔧 Step 5: CRUD Operations (The Laravel Way)

Create a Document

Post::create([
    'title' => 'My First Post',
    'content' => 'Hello MongoDB!',
    'tags' => ['laravel', 'nosql']
]);

Read Documents

$posts = Post::where('tags', 'laravel')->get();

Update

$post = Post::first();
$post->update(['content' => 'Updated content']);

Delete

Post::where('title', 'My First Post')->delete();

✅ Just like MySQL, but more flexible!


🧬 Step 6: Embedded Documents (Nested Data)

Let’s say each post has comments:

class Comment extends Model
{
    protected $fillable = ['author', 'message'];
}

class Post extends Model
{
    public function comments()
    {
        return $this->embedsMany(Comment::class);
    }
}

Add a Comment

$post = Post::first();
$post->comments()->create([
    'author' => 'John Doe',
    'message' => 'Great post!'
]);

Now the comment is stored inside the post document.

🧠 This is more efficient than foreign keys + joins in many cases.


🔍 Step 7: Raw Queries & Aggregations

Aggregation Pipeline Example

$pipeline = [
    ['$match' => ['tags' => 'laravel']],
    ['$group' => ['_id' => '$tags', 'count' => ['$sum' => 1]]]
];

$results = Post::raw(function ($collection) use ($pipeline) {
    return $collection->aggregate($pipeline);
});

🧊 Step 8: Advanced Features

🗃️ Cache Driver

Use MongoDB as your cache store in config/cache.php:

'default' => 'mongodb',

Set TTL index for expiration.

📬 Queue Driver

Use MongoDB as your queue backend with:

QUEUE_CONNECTION=mongodb

Jobs are stored in a Mongo collection and processed normally.

🧾 File Storage with GridFS

GridFS lets you store large files in MongoDB. Configure it via Laravel Filesystem:

'disks' => [
    'gridfs' => [
        'driver' => 'mongodb',
        'bucket' => 'my_files'
    ],
],

🚧 Common Pitfalls & Fixes

Problem Solution
Class not found: MongoDB\Client Install mongodb PHP extension
Collections not showing MongoDB creates collections lazily—insert something first
Can't connect to Atlas Whitelist your IP in Atlas dashboard
Schema errors You don't need strict schema—Mongo is flexible

🎯 Use Cases

MongoDB is perfect for:

  • 📈 Analytics & logs
  • 🌐 Real-time dashboards
  • 🧠 AI metadata storage
  • 📷 File-heavy apps (with GridFS)
  • 🛒 E-commerce with dynamic products

🧾 Recap: MongoDB + Laravel 12

✅ Easy setup with mongodb/laravel-mongodb
✅ Supports Eloquent, Query Builder, raw driver
✅ Perfect for schema-less, embedded data
✅ Integrates with queues, caching, and file storage
✅ Ideal for modern, scalable applications


🚀 Your Turn!

You’ve got the tools. Now it’s time to build. Here are some ideas to try:

  • Create a nested comment system for a blog
  • Store product variations using flexible schemas
  • Upload user files using GridFS
  • Mix MongoDB + MySQL in the same app for hybrid architecture

Laravel 12 and MongoDB together give you the best of both worlds: developer ergonomics and modern database power.


🙋 FAQ (Beginners Ask These A Lot)

Q1: Do I need to run migrations for MongoDB?
A: Not unless you need indexes. Collections are created on the fly.

Q2: Can I use MongoDB and MySQL together in Laravel?
A: Yes! You can define multiple connections and assign them to different models.

Q3: Can I run full-text or geospatial searches?
A: Absolutely. MongoDB supports both via special indexes.


Let's Chat

What are you planning to build with Laravel and MongoDB?
Drop a comment below—I’d love to help or hear your ideas!

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts