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

运行MongoDB搜索查询

在本指南中,您可以学习如何使用Go驱动程序对集合运行MongoDB 搜索查询。MongoDB Search 使您能够对 MongoDB Atlas 上托管的集合执行全文搜索。MongoDB 搜索索引指定搜索行为以及要索引的字段。

The example in this guide uses the movies collection in the sample_mflix database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.

本节展示如何创建聚合管道,以对集合运行 MongoDB 搜索查询。

要运行MongoDB搜索查询,您必须在集合上创建MongoDB搜索索引。要学习如何以编程方式创建MongoDB搜索索引,请参阅索引指南中的MongoDB搜索和MongoDB Vector Search索引部分。

创建 MongoDB Search 索引后,可在您的管道阶段数组中添加 $search 阶段以指定搜索条件。然后,调用 Aggregate() 方法并将管道数组作为参数传递。

提示

要学习;了解有关聚合操作的更多信息,请参阅 聚合指南。

注意

Atlas和 Community Edition 版本要求

$search 聚合管道操作符仅适用于在运行 MongoDB v4.2 或更高版本的MongoDB Atlas集群上托管的集合,或者运行 MongoDB v8.2 或更高版本的MongoDB Community Edition集群上托管的集合。集合必须包含在MongoDB 搜索索引中。要了解有关此操作符所需设置和功能的更多信息,请参阅MongoDB 搜索文档。

此示例通过执行以下操作来运行MongoDB 搜索查询:

  • 创建一个 $search 阶段,指示驱动程序查询title字段包含单词 "Alabama" 的文档

  • 创建一个 $project 阶段,指示驱动程序在查询结果中包含 title 字段

  • 将管道阶段传递到 Aggregate() 方法并打印结果

// Defines the pipelinesearchStage := bson.D{{"$search", bson.D{ {"text", bson.D{ {"path", "title"}, {"query", "Alabama"}, }},}}}projectStage := bson.D{{"$project", bson.D{{"title", 1}}}} // Runs the pipelinecursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, projectStage})if err != nil { panic(err)} // Prints the resultsvar results []bson.Dif err = cursor.All(ctx, &results); err != nil { panic(err)}for _, result := range results { fmt.Println(result)}

要了解有关 MongoDB Search 的更多信息,请参阅 MongoDB Search 指南和 Atlas 文档中的 $search 管道阶段参考。

要学习;了解有关 Aggregate() 方法的详情,请参阅API文档。