You can find multiple documents in a collection by using the Find()
method.
Example
Tip
Read the Usage Examples to learn how to run this example.
This example uses the following Restaurant
struct as a model for documents
in the restaurants
collection:
// Retrieves documents that match a query filter by using the Go driver package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Creates a Restaurant struct as a model for documents in the restaurants collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") // Creates a query filter to match documents in which the "cuisine" // is "Italian" filter := bson.D{{"cuisine", "Italian"}} // Retrieves documents that match the query filter cursor, err := coll.Find(context.TODO(), filter) if err != nil { panic(err) } // Unpacks the cursor into a slice var results []Restaurant if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } // Prints the results of the find operation as structs for _, result := range results { output, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", output) } }
The following example matches documents in the restaurants
collection
in which the cuisine
is "Italian"
, returns a cursor that
references the matched documents, then unpacks the documents into a slice:
// Retrieves documents that match a query filter by using the Go driver package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Creates a Restaurant struct as a model for documents in the restaurants collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") // Creates a query filter to match documents in which the "cuisine" // is "Italian" filter := bson.D{{"cuisine", "Italian"}} // Retrieves documents that match the query filter cursor, err := coll.Find(context.TODO(), filter) if err != nil { panic(err) } // Unpacks the cursor into a slice var results []Restaurant if err = cursor.All(context.TODO(), &results); err != nil { panic(err) } // Prints the results of the find operation as structs for _, result := range results { output, err := json.MarshalIndent(result, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", output) } }
View a fully runnable example
Expected Result
Running the full example prints the following documents, which are stored in
the results
variable as Restaurant
structs:
// results truncated ... { ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... }, { ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... }, { ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... }, ...
Additional Information
To learn more about specifying query filters and handling potential errors, see Find Documents.
To learn more about query operators, see the MongoDB query operator reference documentation.