For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

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 filtercursor, err := coll.Find(context.TODO(), filter)if err != nil { panic(err)} // Unpacks the cursor into a slicevar results []Restaurantif 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.

Rate this page