跳转到主要内容

简介

MongoDB 是最流行的 NoSQL 文档数据库之一。它具备高写入性能(非常适合分析和 IoT)、高可用(通过副本集实现自动故障转移)、水平扩展(分片)以及强大的查询语言(聚合、全文搜索、地理空间查询)。 不同于 SQL 数据库的行 / 列结构,MongoDB 的每一条记录都是 BSON(二进制 JSON)文档。应用中可以以 JSON 的形式读取这些数据。
在 Laravel 中使用 MongoDB 时推荐使用由 MongoDB 官方维护的 mongodb/laravel-mongodb 扩展包。它与 Eloquent 及 Laravel 的各类功能有深度集成。

安装

MongoDB PHP 驱动

连接 MongoDB 需要 mongodb PHP 扩展。使用 Laravel Herdphp.new 时已预装。要手动安装可以使用 PECL。
pecl install mongodb
安装细节请参考 MongoDB PHP 扩展安装指南
请确保 mongodb PHP 扩展在 CLI 和 Web 服务器两端都已启用,两处的配置可能不同。

启动 MongoDB 服务器

本地开发可以使用 MongoDB Community Server。Windows、macOS、Linux、Docker 上的安装方法请参考官方安装指南 使用 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
在云端托管可以使用 MongoDB Atlas。从本地访问 Atlas 集群时,需要把你的 IP 加入项目的 IP 允许列表。

安装 laravel-mongodb 扩展包

使用 Composer 安装 mongodb/laravel-mongodb
composer require mongodb/laravel-mongodb

配置

环境变量

.env 中添加 MongoDB 的连接信息。
MONGODB_URI="mongodb://localhost:27017"
MONGODB_DATABASE="laravel_app"
使用 MongoDB Atlas 时改为 Atlas 的连接字符串。
MONGODB_URI="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority"
MONGODB_DATABASE="laravel_app"

config/database.php

config/database.phpconnections 数组中添加 mongodb 连接。
'connections' => [

    // ... 已有连接 ...

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

],
如果同时使用 MySQL 等关系型数据库和 MongoDB,可以保留 default,只增加一个 mongodb 连接,然后按模型切换连接。

主要功能

Eloquent 模型

继承 MongoDB\Laravel\Eloquent\Model 后,你几乎可以像使用普通 Eloquent 模型一样操作 MongoDB。
<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class Article extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'articles'; // 集合名(省略时会根据类名自动推断)

    protected $fillable = [
        'title',
        'body',
        'tags',
        'published_at',
    ];
}
MongoDB 是无模式的,不需要迁移。保存文档时集合会自动创建。

基本的 CRUD 操作

与普通 Eloquent 一样。
use App\Models\Article;

// 创建
$article = Article::create([
    'title' => 'MongoDB 入门',
    'body' => 'MongoDB 是一种面向文档的数据库。',
    'tags' => ['nosql', 'mongodb', 'laravel'],
    'published_at' => now(),
]);

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

// 更新
$article->update(['title' => 'MongoDB 入门(修订版)']);

// 删除
$article->delete();

数组与嵌套文档

MongoDB 的数组和嵌套文档也可以直接使用。
// 向数组字段 push
$article->push('tags', 'database');

// 从数组字段 pull
$article->pull('tags', 'nosql');

// 查询嵌套文档
$articles = Article::where('meta.author', 'Taylor')->get();

查询构造器

MongoDB 的查询构造器可以用来写更复杂的查询。更多细节请参考 laravel-mongodb 查询构造器文档
use Illuminate\Support\Facades\DB;

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

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

缓存驱动

MongoDB 缓存驱动使用 TTL 索引自动删除过期条目。更多细节请参考 缓存驱动文档 config/cache.php 中添加一个 store。
'stores' => [

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

],
.env 中将缓存驱动切换为 MongoDB。
CACHE_STORE=mongodb

队列驱动

MongoDB 也可以作为队列驱动使用。详情请参考队列驱动文档 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,
    ],

],
.env 中把队列连接切到 MongoDB。
QUEUE_CONNECTION=mongodb

使用 GridFS 存储文件

可以借助 MongoDB 的 GridFS 存储文件,通过 Flysystem 的 GridFS 适配器使用。详情请参考 GridFS 文档
composer require league/flysystem-gridfs
config/filesystems.php 中添加磁盘。
'disks' => [

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

],
use Illuminate\Support\Facades\Storage;

// 上传文件
Storage::disk('gridfs')->put('file.pdf', $contents);

// 读取文件
$contents = Storage::disk('gridfs')->get('file.pdf');

向量检索(Vector Search)

通过 MongoDB Atlas Vector Search,可以基于向量嵌入进行相似度检索。将文本、图片、音频等数据向量化后存储,就能查询与目标向量最接近的文档,非常适合 AI / 机器学习场景。
向量检索仅在 MongoDB Atlas 上可用,本地的 MongoDB Community Server 或自托管环境不支持。使用前需要先在 Atlas 控制台创建 Vector Search 索引。
在查询构造器上使用 vectorSearch 方法。
use App\Models\Article;

// 从查询字符串生成嵌入(例如通过 OpenAI API)
$queryVector = getEmbedding('什么是 MongoDB'); // float[] 数组

$results = Article::query()->vectorSearch(
    index: 'vector_index',   // Atlas Vector Search 索引名
    path: 'embedding',       // 存放向量的字段名
    queryVector: $queryVector,
    limit: 10,               // 返回文档数量
    numCandidates: 100,      // 候选数量(ANN 搜索)
);

// 每个文档会附加 vectorSearchScore
foreach ($results as $result) {
    echo $result->title . ': ' . $result->vectorSearchScore;
}

全文检索(Scout 引擎)

mongodb Scout 引擎让你可以在 MongoDB 上使用 Laravel Scout 的全文检索能力。内部基于 MongoDB Atlas Search,支持模糊搜索、通配符等。详情请参考 Scout 引擎文档
MongoDB Scout 引擎同样只在 MongoDB Atlas 上可用。Scout 的索引集合与模型的集合必须使用不同的集合。config/scout.php 中的 prefix(默认是应用名)会自动生效。
.env 中将 Scout 驱动设为 mongodb
SCOUT_DRIVER=mongodb
在模型上添加 Searchable trait。
use Laravel\Scout\Searchable;
use MongoDB\Laravel\Eloquent\Model;

class Article extends Model
{
    use Searchable;

    // 指定要放入搜索索引的字段
    public function toSearchableArray(): array
    {
        return [
            'title' => $this->title,
            'body'  => $this->body,
            'tags'  => $this->tags,
        ];
    }
}
创建 Scout 索引并将现有数据导入。
php artisan scout:index articles
php artisan scout:import "App\Models\Article"
使用标准的 Scout API 进行搜索。
// 全文检索
$results = Article::search('MongoDB Laravel')->get();

// 带过滤的检索
$results = Article::search('查询构造器')
    ->where('status', 'published')
    ->paginate(15);

与 MySQL 混用

Laravel 可以同时使用 MySQL 与 MongoDB,通过模型的 $connection 属性指定连接即可。
// 使用 MySQL 的常规 Eloquent 模型
class User extends \Illuminate\Database\Eloquent\Model
{
    protected $connection = 'mysql';
}

// 使用 MongoDB 的模型
class Article extends \MongoDB\Laravel\Eloquent\Model
{
    protected $connection = 'mongodb';
}
若要在 MySQL 模型和 MongoDB 模型之间建立关联,请参考混合关联

小结

  1. 通过 pecl install mongodb 安装 PHP 扩展
  2. 启动 MongoDB 服务器(本地、Docker 或 Atlas)
  3. 通过 composer require mongodb/laravel-mongodb 安装扩展包
  4. .env 中配置 MONGODB_URIMONGODB_DATABASE
  5. config/database.php 中添加 mongodb 连接
特性MongoDBMySQL
数据模型文档(JSON/BSON)表(行 / 列)
模式无模式(灵活)固定模式
扩展水平扩展方便主要通过纵向扩展
事务支持多文档事务(v4+)完整 ACID
适用场景日志、分析、IoT、结构灵活的数据结构化数据、复杂关联
功能配置位置
Eloquent 模型继承 MongoDB\Laravel\Eloquent\Model
查询构造器DB::connection('mongodb')->collection(...)
缓存config/cache.php + CACHE_STORE=mongodb
队列config/queue.php + QUEUE_CONNECTION=mongodb
文件存储config/filesystems.php + GridFS 适配器
向量检索Model::query()->vectorSearch(...)(需要 Atlas)
全文检索SCOUT_DRIVER=mongodb + Searchable trait(需要 Atlas)

下一步

laravel-mongodb 官方文档

Eloquent、查询构造器、关联等全部功能的完整参考

快速开始

快速了解 MongoDB 与 Laravel 的基本用法

数据库配置

Laravel 数据库连接配置基础

Eloquent 入门

Eloquent ORM 的基础用法
最后修改于 2026年7月13日

相关主题

搜索