Docs Menu
Docs Home
/ / /
Go Driver

Run an Atlas Search Query

In this guide, you can learn how to use the Go driver to run Atlas Search queries on a collection. Atlas Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. Atlas Search indexes specify the behavior of the search and which fields to index.

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 Get Started with Atlas guide.

This section shows how to create an aggregation pipeline to run an Atlas Search query on a collection. In your array of pipeline stages, add the $search stage to specify the search criteria. Then, call the Aggregate() method and pass your pipeline array as a parameter.

Tip

To learn more about aggregation operations, see the Aggregation guide.

Before running an Atlas Search query, you must create an Atlas Search index on your collection. To learn how to programmatically create an Atlas Search index, see the Atlas Search and Atlas Vector Search Indexes section of the Indexes guide.

This example runs an Atlas Search query by performing the following actions:

  • Creates a $search stage that instructs the driver to query for documents in which the title field contains the word "Alabama"

  • Creates a $project stage that instructs the driver to include the title field in the query results

  • Passes the pipeline stages to the Aggregate() method and prints the results

// 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'
}

To learn more about Atlas Search, see Atlas Search in the Atlas documentation.

To learn more about the Aggregate() method, see the API documentation.

Back

Run a Database Command

On this page