Find Multiple Documents
This version of the documentation is archived and no longer supported. View the current documentation to learn how to upgrade your version of the MongoDB Go Driver.
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:
type Restaurant struct { ID primitive.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} }
The following example matches documents in the restaurants
collection
in which the cuisine
is "Italian", returning all documents matched:
coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"cuisine", "Italian"}} cursor, err := coll.Find(context.TODO(), filter) if err != nil { panic(err) }
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 Retrieve Data.
To learn more about query operators, see the MongoDB query operator reference documentation.