Docs Menu

Docs HomeGo

Find a Document

You can retrieve a single document from a collection by using the FindOne() method.


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 name is "Bagels N Buns", returning the first document matched:

coll := client.Database("sample_restaurants").Collection("restaurants")
filter := bson.D{{"name", "Bagels N Buns"}}
var result Restaurant
err = coll.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
// This error means your query did not match any documents.

View a fully runnable example

Running the full example prints the following document, which is stored in the result variable as a Restaurant struct:

// results truncated
"ID": "5eb3d668b31de5d588f42950",
"Name": "Bagels N Buns",
"RestaurantId": "40363427"
"Address": [...],
"Borough": "Staten Island",
"Cuisine": "Delicatessen",
"Grades": [...]

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 OperationsFind Multiple Documents →