-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathretrieve.txt
372 lines (272 loc) · 10.8 KB
/
retrieve.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
.. _golang-retrieve:
==============
Retrieve Data
==============
.. meta::
:description: Learn how to retrieve data by using MongoDB Go Driver read operations, including find and aggregation methods.
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to retrieve data from your MongoDB
collections using **read operations**.
Read operations allow you to do the following:
- Retrieve documents from your collections by using :ref:`find operations <golang-retrieve-find>`
- Perform transformations on documents in your collections by using :ref:`aggregation operations <golang-retrieve-aggregation>`
Sample Data
~~~~~~~~~~~
The examples in this guide use the following ``Tea`` struct as a model for documents
in the ``tea`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
:start-after: start-tea-struct
:end-before: end-tea-struct
:language: go
:dedent:
To run the examples in this guide, load these documents into the
``tea`` collection in the ``db`` database by using the following snippet:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
:language: go
:dedent:
:start-after: begin insert docs
:end-before: end insert docs
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
Each document describes the tea variety a customer ordered, their
rating, and the date of the order. These descriptions correspond to the
``item``, ``rating``, and ``date_ordered`` fields.
.. _golang-retrieve-find:
Find Operations
---------------
Use **find operations** to retrieve data from MongoDB. Find operations
consist of the ``Find()`` and ``FindOne()`` methods.
Find All Documents
~~~~~~~~~~~~~~~~~~
The ``Find()`` method expects you to pass a ``Context`` type and a
query filter. The method returns *all* documents that match the filter
as a ``Cursor`` type.
For an example that uses the ``Find()`` method, see the :ref:`golang-find-example`
section of this page. To learn how to access data by using a cursor, see
the :ref:`golang-cursor` guide.
Find One Document
~~~~~~~~~~~~~~~~~
The ``FindOne()`` method expects you to pass a ``Context`` type and a
query filter. The method returns *the first document* that matches the
filter as a ``SingleResult`` type.
For an example that uses the ``FindOne()`` method, see the
:ref:`golang-find-one-example` section of this page. For an example that
uses ``FindOne()`` and queries by using a specific ``ObjectId`` value, see
the :ref:`golang-find-one-by-id` section of this page.
To learn how to access data from a ``SingleResult`` type, see
:ref:`golang-bson-unmarshalling` in the BSON guide.
.. _golang-retrieve-options:
Modify Behavior
~~~~~~~~~~~~~~~
You can modify the behavior of ``Find()`` and ``FindOne()`` by passing
in a ``FindOptions`` and ``FindOneOptions`` type respectively. If you
don't specify any options, the driver uses the default values for each
option.
You can configure the commonly used options in both types with the
following methods:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Method
- Description
* - ``SetCollation()``
- | The type of language collation to use when sorting results.
| Default: ``nil``
* - ``SetLimit()``
- | The maximum number of documents to return.
| Default: ``0``
| This option is not available for ``FindOneOptions``. The
``FindOne()`` method internally uses ``SetLimit(-1)``.
* - ``SetProjection()``
- | The fields to include in the returned documents.
| Default: ``nil``
* - ``SetSkip()``
- | The number of documents to skip.
| Default: ``0``
* - ``SetSort()``
- | The field and type of sort to order the matched documents. You can specify an ascending or descending sort.
| Default: none
.. _golang-find-example:
Find Example
````````````
The following example passes a context, filter, and ``FindOptions`` to
the ``Find()`` method, which performs the following actions:
- Matches documents where the ``rating`` value is between ``5`` and
``9`` (exclusive)
- Sorts the matched documents in ascending order by ``date_ordered``
.. io-code-block::
:copyable: true
.. input:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
:start-after: begin find docs
:end-before: end find docs
:language: go
:dedent:
.. output::
:language: none
:visible: false
{"item":"Sencha","rating":7,"date_ordered":"2009-11-18T05:00:00Z"}
{"item":"Masala","rating":8,"date_ordered":"2009-12-01T05:00:00Z"}
.. _golang-find-one-example:
Find One Example
````````````````
The following example passes a context, filter, and ``FindOneOptions``
to the ``FindOne()`` method, which performs the following actions:
- Matches documents where the ``date_ordered`` value is on or before November
30, 2009
- Skips the first two matched documents
.. io-code-block::
:copyable: true
.. input:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
:start-after: begin find one docs
:end-before: end find one docs
:language: go
:dedent:
.. output::
:language: none
:visible: false
{"item":"Masala","rating":9,"date_ordered":"2009-11-12T05:00:00Z"}
.. _golang-find-one-by-id:
Find One by ObjectId Example
````````````````````````````
This example defines an ``id`` variable with a value of type ``ObjectId``
and uses ``id`` to specify a query filter. The filter matches a document
with an ``_id`` field value that corresponds to the ``id`` variable.
This example queries for the following document based on its ``_id`` value:
.. code-block:: json
:copyable: false
:emphasize-lines: 2
{
_id: ObjectId('65170b42b99efdd0b07d42de'),
item: "Hibiscus",
rating : 4,
date_ordered : 2009-12-18T05:00:00.000+00:00
}
The following code passes the filter and a ``FindOneOptions`` instance
as parameters to the ``FindOne()`` method to perform the following actions:
- Match the document with the specified ``ObjectId`` value
- Project only the ``Item`` and ``Rating`` fields of the matched document
.. io-code-block::
:copyable: true
.. input:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
:start-after: begin objectid
:end-before: end objectid
:language: go
:dedent:
.. output::
:language: none
:visible: false
{"item":"Hibiscus","rating":4}
.. note::
The {+driver-short+} automatically generates a unique ``ObjectId``
value for each document's ``_id`` field, so your ``ObjectId`` value
might differ from the preceding code example. For more information
about the ``_id`` field, see the :ref:`_id Field <golang-insert-id>`
section of the Insert a Document page.
.. _golang-retrieve-aggregation:
Aggregation Operations
----------------------
Use **aggregation operations** to retrieve and transform data from
MongoDB. Perform aggregation operations using the ``Aggregate()``
method.
Aggregation
~~~~~~~~~~~
The ``Aggregate()`` method expects you to pass a ``Context`` type and
an **aggregation pipeline**. An aggregation pipeline defines how to
transform data through stages. Some of the stages are matching
documents, renaming fields, and grouping values.
The method returns the resulting documents in a ``Cursor`` type. If
you omit the :manual:`$match </reference/operator/aggregation/match/#mongodb-pipeline-pipe.-match>`
stage, the pipeline proceeds using all documents in the collection.
To learn how to access data in a cursor, see :ref:`golang-cursor`.
Modify Behavior
~~~~~~~~~~~~~~~
The ``Aggregate()`` method optionally takes an ``AggregateOptions``
type, which represents options you can use to modify its behavior. If
you don't specify any options, the driver uses the default values for
each option.
The ``AggregateOptions`` type allows you to configure options with the
following methods:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Method
- Description
* - ``SetAllowDiskUse()``
- | Whether to write to temporary files.
| Default: ``false``
* - ``SetBatchSize()``
- | The number of documents to return in each batch.
| Default: none
* - ``SetBypassDocumentValidation()``
- | Whether to allow the write to opt-out of document level validation.
| Default: ``false``
* - ``SetCollation()``
- | The type of language collation to use when sorting results.
| Default: ``nil``
* - ``SetMaxAwaitTime()``
- | The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query.
| Default: ``nil``
* - ``SetComment()``
- | An arbitrary string or document that allows you to trace the operation through the database profiler, currentOp, and logs.
| Default: ``""``
* - ``SetHint()``
- | The index to use to scan for documents to retrieve.
| Default: ``nil``
* - ``SetLet()``
- | Specifies parameters for the aggregate expression, which improves command readability by separating the variables from the query text.
| Default: none
Example
```````
The following example passes a context and an aggregation pipeline that
performs the following actions:
- Groups reviews by item ordered
- Calculates the average rating for each item
.. io-code-block::
:copyable: true
.. input:: /includes/fundamentals/code-snippets/CRUD/retrieve.go
:start-after: begin aggregate docs
:end-before: end aggregate docs
:language: go
:dedent:
.. output::
:language: none
:visible: false
Sencha had an average rating of 8.5
Hibiscus had an average rating of 4
Masala had an average rating of 9
To learn more about how to construct an aggregation pipeline, see
the MongoDB server manual page on :manual:`Aggregation
</core/aggregation-pipeline/>`.
Additional Information
----------------------
For runnable examples of the find operations, see the following usage
examples:
- :ref:`golang-find-one`
- :ref:`golang-find-multiple`
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-cursor`
- :ref:`golang-skip`
- :ref:`golang-sort-results`
- :ref:`golang-limit`
- :ref:`golang-project`
- :ref:`golang-aggregation`
- :ref:`golang-collations`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `FindOne() <{+api+}/mongo#Collection.FindOne>`__
- `SingleResult <{+api+}/mongo#SingleResult>`__
- `Find() <{+api+}/mongo#Collection.Find>`__
- `FindOptions <{+api+}/mongo/options#FindOptions>`__
- `FindOneOptions <{+api+}/mongo/options#FindOneOptions>`__
- `Cursor <{+api+}/mongo#Cursor>`__
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__
- `AggregateOptions <{+api+}/mongo/options#AggregateOptions>`__