Docs 菜单
Docs 主页
/ / /
Laravel MongoDB
/

模式构建器

Laravel 提供了一个门面来访问模式构建器类 Schema ,它允许您创建和修改表。 外观是类的静态接口,可以使语法更加简洁并提高可测试性。

Laravel 集成支持 Laravel Schema门面中索引和集合管理方法的子集。

要学习;了解有关门面的更多信息,请参阅 Laravel 文档中的 门面 。

以下部分描述了 Laravel 集成中提供的 Laravel模式构建器功能,并展示了如何使用这些功能的示例:

注意

Laravel 集成支持管理索引和集合,但不支持用于数据验证的MongoDB JSON schema。 要学习;了解有关JSON schema验证的更多信息,请参阅服务器手册中的模式验证

Laravel 迁移允许您通过运行Schema门面中包含的方法,以编程方式创建、修改和删除数据库模式。 以下部分说明了在使用MongoDB database时如何编写迁移类以及如何运行它们。

在迁移中修改数据库和集合提供了一种受控方法,可确保应用程序的一致性、版本控制和可逆性。

您可以手动创建迁移类,也可以使用php artisan make:migration命令生成迁移类。 如果生成它们,则必须进行以下更改才能在MongoDB database上执行模式更改:

  • 如果迁移中引用了Illuminate\Database\Schema\Blueprint导入,请将其替换为MongoDB\Laravel\Schema\Blueprint

  • 仅使用 Laravel 集成支持的命令和语法

提示

如果您的默认数据库连接设置为MongoDB database以外的任何连接,请更新以下设置以确保迁移指定正确的数据库:

  • 确保您的connections数组项包含config/database.php文件中有效的mongodb条目

  • 在迁移类的$connection字段中指定"mongodb"

以下示例迁移类包含以下方法:

  • up(),它会在您运行迁移时创建一个集合和一个索引

  • down(),这会在您回滚迁移时删除集合及其上的所有索引

<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use MongoDB\Laravel\Schema\Blueprint;
return new class extends Migration
{
protected $connection = 'mongodb';
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('astronauts', function (Blueprint $collection) {
$collection->index('name');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::drop('astronauts');
}
};

要从类文件运行数据库迁移,请在替换占位符后运行以下命令:

php artisan migrate --path=<path to your migration class file>

此命令运行类文件中的up()函数,以在config/database.php文件指定的数据库中创建集合和索引。

要回滚迁移,请在替换占位符后运行以下命令:

php artisan migrate:rollback --path=<path to your migration class file>

此命令运行类文件中的down()函数以删除集合和相关索引。

要了解有关 Laravel 迁移的更多信息,请参阅 数据库:迁移 在 Laravel 文档中。

要检查集合是否存在,请对迁移文件中的Schema门面调用hasCollection()方法。 您可以使用它来有条件地执行迁移逻辑。

如果存在名为stars的集合,以下示例迁移将创建一个telescopes集合:

$hasCollection = Schema::hasCollection('stars');
if ($hasCollection) {
Schema::create('telescopes');
}

MongoDB 索引是一种数据结构,可通过减少检索查询结果所需的文档数量来提高查询效率。 某些索引(例如地理空间索引)扩展了数据查询的方式。

要使用索引提高查询性能,请确保索引覆盖查询。 要了解有关索引和查询优化的更多信息,请参阅以下MongoDB Server手册条目:

以下部分介绍如何使用模式构建器在集合上创建和删除各种类型的索引。

要创建索引,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 create() 方法。

  2. 向其传递集合名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. 指定 Blueprint实例上的索引创建详细信息。

以下示例迁移在以下集合字段上创建索引:

  • 单字段索引 mission_type

  • launch_locationlaunch_date上的复合索引,指定对launch_date进行降序排序

  • mission_id字段上的唯一索引,指定索引名称"unique_mission_id_idx"

单击 VIEW OUTPUT按钮可查看通过运行迁移创建的索引,包括_id字段上的默认索引:

Schema::create('flights', function (Blueprint $collection) {
$collection->index('mission_type');
$collection->index(['launch_location' => 1, 'launch_date' => -1]);
$collection->unique('mission_id', options: ['name' => 'unique_mission_id_idx']);
});
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { mission_type: 1 }, name: 'mission_type_1' },
{
v: 2,
key: { launch_location: 1, launch_date: -1 },
name: 'launch_location_1_launch_date_-1'
},
{
v: 2,
key: { mission_id: 1 },
name: 'unique_mission_id_idx',
unique: true
}
]

MongoDB 索引选项决定了索引的使用和存储方式。 您可以在调用索引创建方法时指定索引选项,例如在Blueprint实例上调用index()

以下迁移代码展示了如何将排序规则作为索引选项添加到索引中。 单击VIEW OUTPUT按钮可查看通过运行迁移创建的索引,包括_id字段上的默认索引:

Schema::create('passengers', function (Blueprint $collection) {
$collection->index(
'last_name',
name: 'passengers_collation_idx',
options: [
'collation' => [ 'locale' => 'de@collation=phonebook', 'numericOrdering' => true ],
],
);
});
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { last_name: 1 },
name: 'passengers_collation_idx',
collation: {
locale: 'de@collation=phonebook',
caseLevel: false,
caseFirst: 'off',
strength: 3,
numericOrdering: true,
alternate: 'non-ignorable',
maxVariable: 'punct',
normalization: false,
backwards: false,
version: '57.1'
}
}
]

要了解有关索引选项的更多信息,请参阅 MongoDB Server手册中的 适用于所有索引类型的选项 。

您可以使用 Laravel MongoDB辅助方法创建以下类型的索引:

  • 稀疏索引,仅允许包含指定字段的文档的索引项

  • 生存时间 (TTL) 索引,在设定的时间后过期

  • 唯一索引,可防止插入包含索引字段重复值的文档

要创建这些索引类型,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 create() 方法。

  2. create() 传递集合名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. Blueprint实例上调用适合索引类型的辅助方法,并传递索引创建详细信息。

以下迁移代码展示了如何使用索引助手创建稀疏索引和 TTL 索引。 单击VIEW OUTPUT按钮可查看通过运行迁移创建的索引,包括_id字段上的默认索引:

Schema::create('planets', function (Blueprint $collection) {
$collection->sparse('rings');
$collection->expire('last_visible_dt', 86400);
});
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { rings: 1 }, name: 'rings_1', sparse: true },
{
v: 2,
key: { last_visible_dt: 1 },
name: 'last_visible_dt_1',
expireAfterSeconds: 86400
}
]

您可以在索引选项中指定稀疏索引、TTL 索引和唯一索引,从而在单字段或复合索引上指定这些索引。

以下迁移代码展示了如何在单个字段上创建所有三种类型的索引。 单击VIEW OUTPUT按钮可查看通过运行迁移创建的索引,包括_id字段上的默认索引:

Schema::create('planet_systems', function (Blueprint $collection) {
$collection->index('last_visible_dt', options: ['sparse' => true, 'expireAfterSeconds' => 3600, 'unique' => true]);
});
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { last_visible_dt: 1 },
name: 'last_visible_dt_1',
unique: true,
sparse: true,
expireAfterSeconds: 3600
}
]

要了解有关这些索引的更多信息,请参阅 MongoDB Server手册中的 索引属性 。

在 MongoDB 中,地理空间索引允许您查询地理空间坐标数据以了解包含、相交和邻近范围。

要创建地理空间索引,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 create() 方法。

  2. create() 传递集合名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. Blueprint实例上指定地理空间索引创建详细信息。

以下示例迁移在spaceports集合上创建了2d2dsphere地理空间索引。 单击VIEW OUTPUT按钮可查看通过运行迁移创建的索引,包括_id字段上的默认索引:

Schema::create('spaceports', function (Blueprint $collection) {
$collection->geospatial('launchpad_location', '2dsphere');
$collection->geospatial('runway_location', '2d');
});
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { launchpad_location: '2dsphere' },
name: 'launchpad_location_2dsphere',
'2dsphereIndexVersion': 3
},
{ v: 2, key: { runway_location: '2d' }, name: 'runway_location_2d' }
]

要学习;了解有关地理空间索引的更多信息,请参阅服务器手册中的地理空间索引

要从集合中删除索引,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 table() 方法。

  2. 向其传递表名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. 使用 Blueprint实例上的索引名称调用 dropIndex() 方法。

注意

如果删除一个集合,MongoDB 会自动删除与其关联的所有索引。

以下示例迁移从flights集合中删除名为unique_mission_id_idx的索引:

Schema::table('flights', function (Blueprint $collection) {
$collection->dropIndex('unique_mission_id_idx');
});

在MongoDB中,Atlas Search索引支持全文查询。Atlas Vector Search索引支持相似性搜索,可将查询向量与文档中的向量嵌入进行比较。

查看以下指南,学习;了解有关Atlas Search和 Vector Search 功能的更多信息:

  • Atlas Search guide

  • Atlas Vector Search 指南

要创建Atlas Search索引,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 create() 方法。

  2. create() 传递集合名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. 将Atlas索引创建详细信息传递给 Blueprint实例上的 searchIndex() 方法。

此示例迁移在 galaxies集合上创建以下Atlas Search索引:

  • dynamic_index:创建动态映射

  • auto_index:支持对 name字段进行自动完成查询

单击 VIEW OUTPUT 按钮,查看通过运行迁移创建的搜索索引:

Schema::create('galaxies', function (Blueprint $collection) {
$collection->searchIndex([
'mappings' => [
'dynamic' => true,
],
], 'dynamic_index');
$collection->searchIndex([
'mappings' => [
'fields' => [
'name' => [
['type' => 'string', 'analyzer' => 'lucene.english'],
['type' => 'autocomplete', 'analyzer' => 'lucene.english'],
['type' => 'token'],
],
],
],
], 'auto_index');
});
{
"id": "...",
"name": "dynamic_index",
"type": "search",
"status": "READY",
"queryable": true,
"latestDefinition": {
"mappings": { "dynamic": true }
},
...
}
{
"id": "...",
"name": "auto_index",
"type": "search",
"status": "READY",
"queryable": true,
"latestDefinition": {
"mappings": {
"fields": { "name": [
{ "type": "string", "analyzer": "lucene.english" },
{ "type": "autocomplete", "analyzer": "lucene.english" },
{ "type": "token" }
] }
}
},
...
}

要创建 Vector Search 索引,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 create() 方法。

  2. create() 传递集合名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. 将向量索引创建详情传递给 Blueprint实例上的 vectorSearchIndex() 方法。

以下示例迁移在 galaxies集合上创建了一个名为 vs_index 的向量搜索索引。

单击 VIEW OUTPUT 按钮,查看通过运行迁移创建的搜索索引:

Schema::create('galaxies', function (Blueprint $collection) {
$collection->vectorSearchIndex([
'fields' => [
[
'type' => 'vector',
'numDimensions' => 4,
'path' => 'embeddings',
'similarity' => 'cosine',
],
],
], 'vs_index');
});
{
"id": "...",
"name": "vs_index",
"type": "vectorSearch",
"status": "READY",
"queryable": true,
"latestDefinition": {
"fields": [ {
"type": "vector",
"numDimensions": 4,
"path": "embeddings",
"similarity": "cosine"
} ]
},
...
}

要从集合中删除Atlas Search或 Vector Search索引,请执行以下操作:

  1. 在迁移文件中的 Schema 门面上调用 table() 方法。

  2. 向其传递集合名称和带有 MongoDB\Laravel\Schema\Blueprint 参数的回调方法。

  3. 使用 Blueprint实例上的搜索索引名称调用 dropSearchIndex() 方法。

以下示例迁移从galaxies集合中删除名为auto_index的索引:

Schema::table('galaxies', function (Blueprint $collection) {
$collection->dropSearchIndex('auto_index');
});

后退

关系

在此页面上

  • Overview
  • 执行 Laravel 迁移
  • 创建迁移类
  • 运行或回滚迁移
  • 检查集合是否存在
  • 管理索引
  • 创建索引
  • 指定索引选项
  • 创建稀疏索引、 TTL索引和唯一索引
  • 创建地理空间索引
  • 删除索引
  • 管理Atlas Search和 Vector Search 索引