Docs Menu
Docs Home
/ / /
Go Driver
/ /

Find Multiple Documents

You can find multiple documents in a collection by using the Find() method.

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", returns a cursor that references the matched documents, then unpacks the documents into a slice:

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)
}

View a fully runnable example

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", ... },
...

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.

  • Find()

  • Cursor

Back

Find a Document