Find a Document
You can retrieve a single document from a collection by using the
FindOne()
method.
Example
Tip
Read the Usage Examples to learn how to run this example.
The following example matches documents in the movies
collection
in which the title
is "The Room", returning the first document
matched:
coll := client.Database("sample_mflix").Collection("movies") var result bson.M err = coll.FindOne(context.TODO(), bson.D{{"title", "The Room"}}).Decode(&result) if err != nil { if err == mongo.ErrNoDocuments { // This error means your query did not match any documents. return } panic(err) }
View a fully runnable example
Expected Result
After you run the full example, it returns a SingleResult
object that contains the following document:
{ ... "title": "The Room", "year": 2003, ... }
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.