对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

执行文本查询

在本指南中,您可以学习;了解如何使用 Laravel MongoDB运行文本查询。

您可以使用文本查询来检索在指定字段中包含术语或短语的文档。术语是不包括空白字符的字符序列。短语是具有任意数量的空白字符的一系列术语。

本指南介绍了可用于搜索文本的 Eloquent 模型方法,并提供了示例。要学习有关 Laravel 集成中 Eloquent 模型的更多信息,请参阅“建模数据”部分。

要运行本指南中的代码示例,请完成快速入门教程。 本教程说明如何使用示例数据设置 MongoDB Atlas 实例,并在 Laravel Web 应用程序中创建以下文件:

  • Movie.php 文件,其中包含一个Movie movies模型来表示collection中的文档

  • MovieController.php 文件,其中包含用于运行数据库操作的show()函数

  • browse_movies.blade.php 文件,其中包含用于显示数据库操作结果的 HTML 代码

以下部分介绍如何编辑 Laravel 应用程序中的文件以运行查找操作代码示例并查看预期输出。

在执行文本查询之前,必须在文本值字段上创建文本索引。要学习;了解有关创建索引的更多信息,请参阅模式生成器指南的管理索引部分。

You can perform a text query by using the $text operator followed by the $search field in your query filter that you pass to the where() method. The $text operator performs a text query on the text-indexed fields. The $search field specifies the text to search for.

使用where()方法构建查询后,链接get()方法以检索查询结果。

此示例在 Movie Eloquent 模型上调用 where() 方法,以检索plot字段包含短语 "love story" 的文档。要执行此文本查询,集合必须在 plot字段上具有文本索引。

使用以下语法指定查询:

$movies = Movie::where('$text', ['$search' => '"love story"'])
->get();

要在browse_movies视图中查看查询结果,请编辑MovieController.php文件中的show()函数,使其类似于以下代码:

class MovieController
{
public function show()
{
$movies = Movie::where('$text', ['$search' => '"love story"'])
->get();
return view('browse_movies', [
'movies' => $movies
]);
}
}

A text query assigns a numerical text score to indicate how closely each result matches the string in your query filter. You can sort the results by relevance by using the orderBy() method to sort on the textScore metadata field. You can access this metadata by using the $meta operator:

$movies = Movie::where('$text', ['$search' => '"love story"'])
->orderBy('score', ['$meta' => 'textScore'])
->get();

提示

要学习;了解有关orderBy() 方法的更多信息,请参阅“修改查询输出”指南的“对查询结果进行排序”部分。

要查看演示如何使用 Laravel 集成执行查找操作的可运行代码示例,请参阅以下用法示例:

要了解如何根据过滤器条件检索数据,请参阅检索 MongoDB 数据指南。