索引和搜索
索引和搜索
MongoDB Atlas 提供了一个全文搜索引擎,可用于搜索集合中的文档。
Atlas Search 由 Apache Lucene 提供支持。
创建索引
我们将使用 Atlas 控制台,在我们加载的示例数据中,为 "sample_mflix" 数据库创建一个索引。这些示例数据来自 聚合入门 部分。
- 从 Atlas 控制台,点击您的 集群名称,然后点击 Search 选项卡。
- 点击 Create Search Index 按钮。
- 使用 Visual Editor 并点击 Next。
- 为您的索引命名,选择您要索引的数据库和集合,然后点击 Next。
- 如果将索引命名为 "default",则在
$search
管道阶段无需指定索引名称。 - 选择
sample_mflix
数据库和movies
集合。
- 如果将索引命名为 "default",则在
- 点击 Create Search Index 并等待索引完成。
运行查询
要使用我们的搜索索引,我们将在聚合管道中使用 $search
操作符。
示例
db.movies.aggregate([
{
$search: {
index: "default", // optional unless you named your index something other than "default"
text: {
query: "star wars",
path: "title"
},
},
},
{
$project: {
title: 1,
year: 1,
}
}
])
自己动手试一试 »
此聚合管道的第一阶段将返回 movies
集合中,在 title
字段包含 "star" 或 "wars" 字样的所有文档。
第二阶段将从每个文档中提取 title
和 year
字段。