Skip to content

Commit d3e37a9

Browse files
DOCSP-18987 common find options (#67)
* added common options
1 parent e9ac81f commit d3e37a9

File tree

2 files changed

+174
-16
lines changed

2 files changed

+174
-16
lines changed

source/fundamentals/crud/read-operations/retrieve.txt

Lines changed: 142 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,57 @@ filter as a ``SingleResult`` type.
6363
To learn how to access data in a ``SingleResult`` see the :ref:`BSON
6464
<bson-unmarshalling>` guide.
6565

66+
Modify Behavior
67+
~~~~~~~~~~~~~~~
68+
69+
You can modify the behavior of ``Find()`` and ``FindOne()`` by passing
70+
in a ``FindOptions`` and ``FindOneOptions`` type respectively. If you
71+
don't specify any options, the driver uses the default values for each
72+
option.
73+
74+
You can configure the commonly used options in both types with the
75+
following functions:
76+
77+
.. list-table::
78+
:widths: 30 70
79+
:header-rows: 1
80+
81+
* - Function
82+
- Description
83+
84+
* - ``SetCollation()``
85+
- | The type of language collation to use when sorting results.
86+
| Default: ``nil``
87+
88+
* - ``SetLimit()``
89+
- | The maximum number of documents to return.
90+
| Default: ``0``
91+
92+
.. note::
93+
94+
This option is not available for ``FindOneOptions``. The
95+
``FindOne()`` function internally uses ``SetLimit(-1)``.
96+
97+
* - ``SetProjection()``
98+
- | The fields to include in the returned documents.
99+
| Default: ``nil``
100+
101+
* - ``SetSkip()``
102+
- | The number of documents to skip.
103+
| Default: ``0``
104+
105+
* - ``SetSort()``
106+
- | The field and type of sort to order the matched documents. You can specify an ascending or descending sort.
107+
| Default: none
108+
66109
Example
67110
```````
68111

69-
The following example passes a context and a filter to the ``Find()``
70-
function, which matches documents where the ``ratings`` field falls
71-
between ``5`` and ``10``:
112+
The following example passes a context, filter, and ``FindOptions`` to
113+
the ``Find()`` function, which performs the following actions:
114+
115+
- Matches documents where the ``rating`` falls between ``5`` and ``10``
116+
- Returns the ``type`` and ``rating``, but excludes the ``_id``
72117

73118
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
74119
:language: go
@@ -81,8 +126,31 @@ After running this example, the output resembles the following:
81126
.. code-block:: none
82127
:copyable: false
83128

84-
[_id:ObjectID("...") type:Masala rating:7 ]
85-
[_id:ObjectID("...") type:Earl Grey rating:9 ]
129+
[{type Masala} {rating 7}]
130+
[{type Earl Grey} {rating 9}]
131+
132+
Example
133+
```````
134+
135+
The following example passes a context, filter, and ``FindOneOptions``
136+
to the ``FindOne()`` function, which performs the following actions:
137+
138+
- Matches all documents
139+
- A descending sort on the ``rating`` field
140+
- Returns the ``type`` and ``rating``, but excludes the ``_id``
141+
142+
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
143+
:language: go
144+
:dedent:
145+
:start-after: begin find one docs
146+
:end-before: end find one docs
147+
148+
After running this example, the output resembles the following:
149+
150+
.. code-block:: none
151+
:copyable: false
152+
153+
[{type Masala} {rating 10}]
86154

87155
.. _retrieve-aggregation:
88156

@@ -108,10 +176,65 @@ stage, the pipeline proceeds using all documents in the collection.
108176
.. To learn how to access data in a cursor, see the :doc:`Cursor
109177
.. </fundamentals/crud/read-operations/cursor>` guide.
110178

179+
Modify Behavior
180+
~~~~~~~~~~~~~~~
181+
182+
The ``Aggregate()`` function optionally takes an ``AggregateOptions``
183+
type, which represents options you can use to modify its behavior. If
184+
you don't specify any options, the driver uses the default values for
185+
each option.
186+
187+
The ``AggregateOptions`` type allows you to configure options with the
188+
following functions:
189+
190+
.. list-table::
191+
:widths: 30 70
192+
:header-rows: 1
193+
194+
* - Function
195+
- Description
196+
197+
* - ``SetAllowDiskUse()``
198+
- | Whether to write to temporary files.
199+
| Default: ``false``
200+
201+
* - ``SetBatchSize()``
202+
- | The number of documents to return in each batch.
203+
| Default: none
204+
205+
* - ``SetBypassDocumentValidation()``
206+
- | Whether to allow the write to opt-out of document level validation.
207+
| Default: ``false``
208+
209+
* - ``SetCollation()``
210+
- | The type of language collation to use when sorting results.
211+
| Default: ``nil``
212+
213+
* - ``SetMaxTime()``
214+
- | The maximum amount of time in milliseconds to allow the query to run.
215+
| Default: ``nil``
216+
217+
* - ``SetMaxAwaitTime()``
218+
- | The maximum amount of time in milliseconds for the server to wait on new documents to satisfy a tailable cursor query.
219+
| Default: ``nil``
220+
221+
* - ``SetComment()``
222+
- | An arbitrary string to help trace the operation through the database profiler, currentOp and logs.
223+
| Default: ``""``
224+
225+
* - ``SetHint()``
226+
- | The index to use to scan for documents to retrieve.
227+
| Default: ``nil``
228+
229+
* - ``SetLet()``
230+
- | Specifies parameters for the aggregate expression, which improves command readability by separating the variables from the query text.
231+
| Default: none
232+
111233
Example
112234
```````
113235

114-
The following example passes a context and an aggregation pipeline that:
236+
The following example passes a context and an aggregation pipeline that
237+
performs the following actions:
115238

116239
- Groups reviews by types
117240
- Calculates the average rating of each type
@@ -143,11 +266,17 @@ examples:
143266
- :doc:`Find a Document </usage-examples/findOne>`
144267
- :doc:`Find Multiple Documents </usage-examples/find>`
145268

146-
.. For more information on how to specify a query, see the :doc:`Specify
147-
.. a Query </fundamentals/crud/query-document>` guide.
269+
For more information about the read operations mentioned, see the
270+
following guides:
271+
272+
- :doc:`Skip Returned Results </fundamentals/crud/read-operations/skip>`
273+
- :doc:`Sort Results </fundamentals/crud/read-operations/sort>`
274+
- :doc:`Limit the Number of Returned Results </fundamentals/crud/read-operations/limit>`
148275

149-
.. For more information on aggregation, see the
150-
.. :doc:`Aggregation </fundamentals/aggregation>` guide.
276+
.. - :doc:`Specify Which Fields to Return </fundamentals/crud/read-operations/project>`
277+
.. - :doc:`Collations </fundamentals/collations>`
278+
.. - :doc:`Specify a Query </fundamentals/crud/query-document>` guide.
279+
.. - :doc:`Aggregation </fundamentals/aggregation>` guide.
151280

152281
API Documentation
153282
~~~~~~~~~~~~~~~~~
@@ -156,7 +285,10 @@ For more information on any of the functions or types discussed in this
156285
guide, see the following API Documentation:
157286

158287
- `Find() <{+api+}/mongo#Collection.Find>`__
288+
- `FindOptions <{+api+}/mongo/options#FindOptions>`__
289+
- `FindOneOptions <{+api+}/mongo/options#FindOneOptions>`__
159290
- `Cursor <{+api+}/mongo#Cursor>`__
160291
- `FindOne() <{+api+}/mongo#Collection.FindOne>`__
161292
- `SingleResult <{+api+}/mongo#SingleResult>`__
162293
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__
294+
- `AggregateOptions <{+api+}/mongo/options#AggregateOptions>`__

source/includes/fundamentals/code-snippets/CRUD/retrieve.go

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import (
1313

1414
func main() {
1515
var uri string
16-
if uri = os.Getenv("MONGODB_URI"); uri == "" {
17-
log.Fatal("You must set your `MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
16+
if uri = os.Getenv("DRIVER_REF_URI"); uri == "" {
17+
log.Fatal("You must set your 'MONGODB_URI' environmental variable. See\n\t https://docs.mongodb.com/drivers/go/current/usage-examples/")
1818
}
1919

2020
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
@@ -27,6 +27,8 @@ func main() {
2727
panic(err)
2828
}
2929
}()
30+
31+
client.Database("tea").Collection("ratings").Drop(context.TODO())
3032

3133
// begin insert docs
3234
coll := client.Database("tea").Collection("ratings")
@@ -41,24 +43,31 @@ func main() {
4143
if err != nil {
4244
panic(err)
4345
}
44-
fmt.Printf("Number of documents inserted: %d\n", len(result.InsertedIDs))
46+
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
4547
// end insert docs
4648

49+
for _, id := range result.InsertedIDs {
50+
fmt.Printf("\t%s\n", id)
51+
}
52+
53+
fmt.Println("Find:")
4754
// begin find docs
48-
filter := bson.D{
55+
findFilter := bson.D{
4956
{"$and",
5057
bson.A{
5158
bson.D{{"rating", bson.D{{"$gt", 5}}}},
5259
bson.D{{"rating", bson.D{{"$lt", 10}}}},
5360
}},
5461
}
62+
findProjection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
63+
findOptions := options.Find().SetProjection(findProjection)
5564

56-
findCursor, findErr := coll.Find(context.TODO(), filter)
65+
findCursor, findErr := coll.Find(context.TODO(), findFilter, findOptions)
5766
if findErr != nil {
5867
panic(findErr)
5968
}
6069

61-
var findResults []bson.M
70+
var findResults []bson.D
6271
if findErr = findCursor.All(context.TODO(), &findResults); findErr != nil {
6372
panic(findErr)
6473
}
@@ -67,6 +76,23 @@ func main() {
6776
}
6877
// end find docs
6978

79+
fmt.Println("Find One:")
80+
// begin find one docs
81+
findOneFilter := bson.D{}
82+
findOnesort := bson.D{{"rating", -1}}
83+
findOneprojection := bson.D{{"type", 1}, {"rating", 1}, {"_id", 0}}
84+
findOneOptions := options.FindOne().SetSort(findOnesort).SetProjection(findOneprojection)
85+
86+
var findOneResult bson.D
87+
findOneErr := coll.FindOne(context.TODO(), findOneFilter, findOneOptions).Decode(&findOneResult)
88+
if findOneErr != nil {
89+
panic(findOneErr)
90+
}
91+
92+
fmt.Println(findOneResult)
93+
// end find one docs
94+
95+
fmt.Println("Aggregation:")
7096
// begin aggregate docs
7197
groupStage := bson.D{
7298
{"$group", bson.D{

0 commit comments

Comments
 (0)