Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Go 驱动程序

运行 Atlas Search 查询

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

本指南中的示例使用来自 Atlas 示例数据集sample_mflix 数据库中的 movies 集合。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅Atlas 入门指南

本节将介绍如何创建聚合管道以在集合上运行 Atlas Search 查询。

要运行Atlas Search查询,您必须在集合上创建Atlas Search索引。要学习;了解如何以编程方式创建Atlas Search索引,请参阅指南的 golang-atlas-search-indexes 部分。

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

提示

如需了解更多关于聚合操作的信息,请参阅聚合指南。

此示例通过执行以下操作来运行Atlas Search查询:

  • 创建一个 $search 阶段,指示驾驶员查询title字段包含单词 "Alabama" 的文档

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

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

// Defines the pipeline
searchStage := bson.D{{"$search", bson.D{
{"text", bson.D{
{"path", "title"},
{"query", "Alabama"},
}},
}}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}}}}
// Runs the pipeline
cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, projectStage})
if err != nil {
panic(err)
}
// Prints the results
var results []bson.D
if err = cursor.All(ctx, &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
{
_id: new ObjectId('...'),
title: 'Alabama Moon'
}
{
_id: new ObjectId('...'),
title: 'Crazy in Alabama'
}
{
_id: new ObjectId('...'),
title: 'Sweet Home Alabama'
}

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

要了解有关 Aggregate() 方法的更多信息,请参阅 API 文档。

后退

时间序列

在此页面上