Docs Menu
Docs Home
/ /

Run a MongoDB Search Query

In this guide, you can learn how to use the Go driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB 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 MongoDB Get Started <https://www.mongodb.com/ja-jp/docs/get-started/?language=go guide.

This section shows how to create an aggregation pipeline to run a MongoDB Search query on a collection.

To run a MongoDB Search query, you must create a MongoDB Search index on your collection. To learn how to programmatically create a MongoDB Search index, see the MongoDB Search and MongoDB Vector Search Indexes section of the Indexes guide.

After you create a MongoDB Search index, add the $search stage in your array of pipeline stages 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.

This example runs a MongoDB 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 MongoDB Search, see the MongoDB Search guides and the $search pipeline stage reference in the Atlas documentation.

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

Back

Time Series

On this page