Skip to content

Commit 5e82de3

Browse files
biniona-mongodbChris ChokevinAlbsIsabella Siu
authored
Docsp 13855 usage example find a doc (#2)
Docsp 13855 Usage Example Find a Document Co-authored-by: Chris Cho <[email protected]> Co-authored-by: Kevin Albertson <[email protected]> Co-authored-by: Isabella Siu <[email protected]>
1 parent 19d3e5c commit 5e82de3

File tree

6 files changed

+155
-1
lines changed

6 files changed

+155
-1
lines changed

source/fundamentals/context.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
TODO: Discussion of the ``context`` package

source/includes/sample-data-note.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.. note::
2+
3+
This example uses the MongoDB Atlas sample dataset.
4+
You can learn how to set up a free-tier Atlas cluster with the sample
5+
dataset by following our :doc:`quick start guide </quick-start>`.

source/usage-examples.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ Usage Examples
66

77
.. toctree::
88

9-
..
109
/usage-examples/find-operations
10+
11+
..
1112
/usage-examples/insert-operations
1213
/usage-examples/update-operations
1314
/usage-examples/delete-operations
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"title":"The Room","imdb":{"rating":3.5,"votes":25673,"id":368226}}

source/usage-examples/findOne.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
7+
"go.mongodb.org/mongo-driver/bson"
8+
"go.mongodb.org/mongo-driver/mongo"
9+
"go.mongodb.org/mongo-driver/mongo/options"
10+
)
11+
12+
// Replace the uri string with your MongoDB deployment's connection string.
13+
const uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority"
14+
15+
func main() {
16+
ctx := context.TODO()
17+
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
18+
if err != nil {
19+
panic(err)
20+
}
21+
defer func() {
22+
if err = client.Disconnect(ctx); err != nil {
23+
panic(err)
24+
}
25+
}()
26+
27+
coll := client.Database("sample_mflix").Collection("movies")
28+
var result bson.D
29+
opts := options.FindOne().
30+
SetProjection(bson.D{{"_id", 0}, {"title", 1}, {"imdb", 1}}).
31+
SetSort(bson.D{{"imdb.rating", -1}})
32+
err = coll.FindOne(ctx, bson.D{{"title", "The Room"}}, opts).Decode(&result)
33+
if err != nil {
34+
if err == mongo.ErrNoDocuments {
35+
// This error means your query did not match any documents.
36+
return
37+
}
38+
panic(err)
39+
}
40+
41+
relaxedJSONBytes, err := bson.MarshalExtJSON(result, false, false)
42+
if err != nil {
43+
panic(err)
44+
}
45+
fmt.Printf("%s\n", relaxedJSONBytes)
46+
}

source/usage-examples/findOne.txt

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,103 @@ Find a Document
33
===============
44

55
.. default-domain:: mongodb
6+
7+
You can retrieve a single document from your collection with the
8+
``Collection.FindOne()`` method.
9+
10+
..
11+
method
12+
13+
The ``FindOne()`` method takes a filter document. Calling the ``FindOne()``
14+
method retrieves a document from your MongoDB instance that matches your
15+
filter document. If you pass the ``FindOne()`` method an empty filter document,
16+
MongoDB considers your entire collection when retrieving your document. For more
17+
information on documents in the MongoDB Go driver, see our
18+
:doc:`guide on data formats </fundamentals/data-formats>`.
19+
20+
You must pass the ``FindOne()`` method a ``context.Context`` interface type
21+
value. For more information on the ``context.Context`` interface and the
22+
``context`` package, see our :doc:`guide on contexts </fundamentals/context>`.
23+
24+
..
25+
options
26+
27+
You can specify options that change the behavior of the ``FindOne()`` method.
28+
One example of an option is **sort**, which instructs your MongoDB instance to
29+
order the matching documents of your collection before it retrieves the
30+
first document. Another example of an option is a **projection**, which
31+
specifies or restricts the fields in your returned document. You can specify
32+
options by passing the ``FindOne()`` method a pointer to a ``FindOneOptions`` struct.
33+
You can configure a ``FindOneOptions`` struct by using setter methods such as the
34+
``FindOneOptions.SetProjection()`` method. For more information on the sort option,
35+
:doc:`see our guide on sorting </fundamentals/crud/read-operations/sort/>`.
36+
For more information on the projection option,
37+
:doc:`see our guide on projections </fundamentals/crud/read-operations/project/>`.
38+
39+
..
40+
return
41+
42+
If the query filter you specified in your ``FindOne()`` method call matches one
43+
or more documents in your collection, it returns the first matched result. The
44+
return type ``SingleResult`` represents a single document returned from a query
45+
to a MongoDB instance. You can call the ``SingleResult.Decode()`` method
46+
to unmarshal a ``SingleResult`` struct type into a variable. Pass the ``Decode()``
47+
method a pointer to the variable that you would like to contain your returned
48+
document.
49+
50+
..
51+
error
52+
53+
When you call the ``Decode()`` method to unmarshal your result, the method
54+
returns an ``error`` interface type which can contain one of the following
55+
values:
56+
57+
- ``nil`` if a document matched your query, and there were no errors retrieving
58+
the document.
59+
- ``ErrNoDocuments`` if no documents matched your query.
60+
- If the driver retrieved your document but could not unmarshal your result, the
61+
``Decode()`` method returns the unmarshaling error.
62+
- If there was an error retrieving your document during execution of the
63+
``FindOne()`` method, the error propagates to the ``Decode()`` method and
64+
the ``Decode()`` method returns the error.
65+
66+
Example
67+
-------
68+
69+
The following code example retrieves a single document from the ``movies``
70+
collection. It uses the following arguments for the ``FindOne()`` method:
71+
72+
- An empty **Context** instance returned from the ``context.TODO()`` function.
73+
- A **filter document** that only matches movies with the title exactly matching
74+
the text ``"The Room"``.
75+
- **Options** that specify a **sort** of matched documents in
76+
descending order by rating, such that the first document has the highest
77+
rating. The options also specify a **projection** for the results so
78+
that the MongoDB instance only sends the ``title`` and ``imdb`` fields of
79+
the retrieved document.
80+
81+
.. include:: /includes/connect-guide-note.rst
82+
83+
.. literalinclude:: findOne.go
84+
:language: go
85+
86+
If you run the example above, you should see a result that looks like this:
87+
88+
.. literalinclude:: findOne-output.txt
89+
:language: none
90+
91+
.. include:: /includes/sample-data-note.rst
92+
93+
For more information on the methods, interfaces, structs, and functions
94+
mentioned on this page, see the following API documentation:
95+
96+
- :go-api:`Collection.FindOne() <mongo#Collection.FindOne>`
97+
- `Context <https://pkg.go.dev/context#Context>`__
98+
- :go-api:`FindOneOptions <mongo/options#FindOneOptions>`
99+
- :go-api:`FindOneOptions.SetProjection() <mongo/options#FindOneOptions.SetProjection>`
100+
- :go-api:`options.FindOne() <mongo/options#FindOne>`
101+
- :go-api:`SingleResult <mongo#SingleResult>`
102+
- :go-api:`SingleResult.Decode() <mongo#SingleResult.Decode>`
103+
- `context.TODO() <https://pkg.go.dev/context#TODO>`__
104+
- :go-api:`bson.D <bson#D>`
105+
- :go-api:`bson.MarshalExtJSON() <bson#MarshalExtJSON>`

0 commit comments

Comments
 (0)