> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB

> 在 Laravel 应用中使用 MongoDB。涵盖驱动安装、配置、Eloquent 模型、查询构造器，以及作为缓存和队列驱动的用法。

## 简介

[MongoDB](https://www.mongodb.com/resources/products/fundamentals/why-use-mongodb) 是最流行的 NoSQL 文档数据库之一。它具备高写入性能（非常适合分析和 IoT）、高可用（通过副本集实现自动故障转移）、水平扩展（分片）以及强大的查询语言（聚合、全文搜索、地理空间查询）。

不同于 SQL 数据库的行 / 列结构，MongoDB 的每一条记录都是 BSON（二进制 JSON）文档。应用中可以以 JSON 的形式读取这些数据。

```mermaid theme={null}
flowchart LR
    A["Laravel<br>应用"] --> B["mongodb/laravel-mongodb<br>扩展包"]
    B --> C["MongoDB PHP 驱动"]
    C --> D["MongoDB 服务器"]

    subgraph features ["主要用途"]
        E["Eloquent 模型"]
        F["查询构造器"]
        G["缓存驱动"]
        H["队列驱动"]
        I["GridFS 文件存储"]
        J["向量检索"]
        K["全文检索 (Scout)"]
    end

    B --> E
    B --> F
    B --> G
    B --> H
    B --> I
    B --> J
    B --> K
```

<Info>
  在 Laravel 中使用 MongoDB 时推荐使用由 MongoDB 官方维护的 `mongodb/laravel-mongodb` 扩展包。它与 Eloquent 及 Laravel 的各类功能有深度集成。
</Info>

## 安装

### MongoDB PHP 驱动

连接 MongoDB 需要 `mongodb` PHP 扩展。使用 [Laravel Herd](https://herd.laravel.com) 或 `php.new` 时已预装。要手动安装可以使用 PECL。

```shell theme={null}
pecl install mongodb
```

安装细节请参考 [MongoDB PHP 扩展安装指南](https://www.php.net/manual/en/mongodb.installation.php)。

<Warning>
  请确保 `mongodb` PHP 扩展在 CLI 和 Web 服务器两端都已启用，两处的配置可能不同。
</Warning>

### 启动 MongoDB 服务器

本地开发可以使用 MongoDB Community Server。Windows、macOS、Linux、Docker 上的安装方法请参考[官方安装指南](https://docs.mongodb.com/manual/administration/install-community/)。

**使用 Docker：**

```yaml theme={null}
# 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:
```

```shell theme={null}
docker compose up -d
```

在云端托管可以使用 [MongoDB Atlas](https://www.mongodb.com/cloud/atlas)。从本地访问 Atlas 集群时，需要把你的 IP 加入项目的 IP 允许列表。

### 安装 laravel-mongodb 扩展包

使用 Composer 安装 `mongodb/laravel-mongodb`。

```shell theme={null}
composer require mongodb/laravel-mongodb
```

## 配置

### 环境变量

在 `.env` 中添加 MongoDB 的连接信息。

```ini theme={null}
MONGODB_URI="mongodb://localhost:27017"
MONGODB_DATABASE="laravel_app"
```

使用 MongoDB Atlas 时改为 Atlas 的连接字符串。

```ini theme={null}
MONGODB_URI="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority"
MONGODB_DATABASE="laravel_app"
```

### config/database.php

在 `config/database.php` 的 `connections` 数组中添加 `mongodb` 连接。

```php theme={null}
'connections' => [

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

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

],
```

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

## 主要功能

### Eloquent 模型

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

```php theme={null}
<?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',
    ];
}
```

<Info>
  MongoDB 是无模式的，不需要迁移。保存文档时集合会自动创建。
</Info>

#### 基本的 CRUD 操作

与普通 Eloquent 一样。

```php theme={null}
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 的数组和嵌套文档也可以直接使用。

```php theme={null}
// 向数组字段 push
$article->push('tags', 'database');

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

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

### 查询构造器

MongoDB 的查询构造器可以用来写更复杂的查询。更多细节请参考 [laravel-mongodb 查询构造器文档](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/query-builder/)。

```php theme={null}
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 索引自动删除过期条目。更多细节请参考 [缓存驱动文档](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/cache/)。

在 `config/cache.php` 中添加一个 store。

```php theme={null}
'stores' => [

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

],
```

在 `.env` 中将缓存驱动切换为 MongoDB。

```ini theme={null}
CACHE_STORE=mongodb
```

### 队列驱动

MongoDB 也可以作为队列驱动使用。详情请参考[队列驱动文档](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/queues/)。

在 `config/queue.php` 中添加连接。

```php theme={null}
'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。

```ini theme={null}
QUEUE_CONNECTION=mongodb
```

### 使用 GridFS 存储文件

可以借助 MongoDB 的 GridFS 存储文件，通过 [Flysystem 的 GridFS 适配器](https://flysystem.thephpleague.com/docs/adapter/gridfs/)使用。详情请参考 [GridFS 文档](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/filesystems/)。

```shell theme={null}
composer require league/flysystem-gridfs
```

在 `config/filesystems.php` 中添加磁盘。

```php theme={null}
'disks' => [

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

],
```

```php theme={null}
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](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/fundamentals/vector-search/)，可以基于向量嵌入进行相似度检索。将文本、图片、音频等数据向量化后存储，就能查询与目标向量最接近的文档，非常适合 AI / 机器学习场景。

<Info>
  向量检索仅在 **MongoDB Atlas** 上可用，本地的 MongoDB Community Server 或自托管环境不支持。使用前需要先在 Atlas 控制台创建 Vector Search 索引。
</Info>

在查询构造器上使用 `vectorSearch` 方法。

```php theme={null}
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](/zh/scout) 的全文检索能力。内部基于 **MongoDB Atlas Search**，支持模糊搜索、通配符等。详情请参考 [Scout 引擎文档](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/scout/)。

<Info>
  MongoDB Scout 引擎同样只在 **MongoDB Atlas** 上可用。Scout 的索引集合与模型的集合必须使用不同的集合。`config/scout.php` 中的 `prefix`（默认是应用名）会自动生效。
</Info>

在 `.env` 中将 Scout 驱动设为 `mongodb`。

```ini theme={null}
SCOUT_DRIVER=mongodb
```

在模型上添加 `Searchable` trait。

```php theme={null}
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 索引并将现有数据导入。

```shell theme={null}
php artisan scout:index articles
php artisan scout:import "App\Models\Article"
```

使用标准的 Scout API 进行搜索。

```php theme={null}
// 全文检索
$results = Article::search('MongoDB Laravel')->get();

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

## 与 MySQL 混用

Laravel 可以同时使用 MySQL 与 MongoDB，通过模型的 `$connection` 属性指定连接即可。

```mermaid theme={null}
flowchart TD
    A["Laravel 应用"] --> B["UserController"]
    A --> C["ArticleController"]
    B --> D["User 模型\n$connection = 'mysql'"]
    C --> E["Article 模型\n$connection = 'mongodb'"]
    D --> F["MySQL"]
    E --> G["MongoDB"]
```

```php theme={null}
// 使用 MySQL 的常规 Eloquent 模型
class User extends \Illuminate\Database\Eloquent\Model
{
    protected $connection = 'mysql';
}

// 使用 MongoDB 的模型
class Article extends \MongoDB\Laravel\Eloquent\Model
{
    protected $connection = 'mongodb';
}
```

<Info>
  若要在 MySQL 模型和 MongoDB 模型之间建立关联，请参考[混合关联](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/eloquent-models/relationships/)。
</Info>

## 小结

<AccordionGroup>
  <Accordion title="安装清单">
    1. 通过 `pecl install mongodb` 安装 PHP 扩展
    2. 启动 MongoDB 服务器（本地、Docker 或 Atlas）
    3. 通过 `composer require mongodb/laravel-mongodb` 安装扩展包
    4. 在 `.env` 中配置 `MONGODB_URI` 与 `MONGODB_DATABASE`
    5. 在 `config/database.php` 中添加 `mongodb` 连接
  </Accordion>

  <Accordion title="MongoDB 与 MySQL 的选型">
    | 特性   | MongoDB           | MySQL      |
    | ---- | ----------------- | ---------- |
    | 数据模型 | 文档（JSON/BSON）     | 表（行 / 列）   |
    | 模式   | 无模式（灵活）           | 固定模式       |
    | 扩展   | 水平扩展方便            | 主要通过纵向扩展   |
    | 事务   | 支持多文档事务（v4+）      | 完整 ACID    |
    | 适用场景 | 日志、分析、IoT、结构灵活的数据 | 结构化数据、复杂关联 |
  </Accordion>

  <Accordion title="功能与配置的对应">
    | 功能          | 配置位置                                                  |
    | ----------- | ----------------------------------------------------- |
    | 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） |
  </Accordion>
</AccordionGroup>

## 下一步

<CardGroup cols={2}>
  <Card title="laravel-mongodb 官方文档" icon="book" href="https://www.mongodb.com/docs/drivers/php/laravel-mongodb/">
    Eloquent、查询构造器、关联等全部功能的完整参考
  </Card>

  <Card title="快速开始" icon="rocket" href="https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/quick-start/">
    快速了解 MongoDB 与 Laravel 的基本用法
  </Card>

  <Card title="数据库配置" icon="database" href="/zh/database">
    Laravel 数据库连接配置基础
  </Card>

  <Card title="Eloquent 入门" icon="table" href="/zh/eloquent">
    Eloquent ORM 的基础用法
  </Card>
</CardGroup>


## Related topics

- [搜索](/zh/search.md)
