-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathretrieve.txt
303 lines (210 loc) · 9.76 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
.. _csharp-retrieve:
=============
Retrieve Data
=============
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: code examples, read, search, cursor
Overview
--------
In this guide, you can learn how to use the {+driver-long+} to retrieve
data from a MongoDB collection by using read operations. You can call the
``Find()`` method to retrieve documents that match a set of criteria.
.. tip:: Interactive Lab
This page includes a short interactive lab that demonstrates how to
retrieve data by using the ``Find()`` method. You can complete this lab
directly in your browser window without installing MongoDB or a code editor.
To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the
top of the page. To expand the lab to a full-screen format, click the
full-screen button (:guilabel:`⛶`) in the top-right corner of the lab pane.
Sample Data
~~~~~~~~~~~
The examples in this guide use the ``sample_restaurants.restaurants`` collection
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`.
The examples on this page use the following ``Restaurant``, ``Address``, and ``GradeEntry``
classes as models:
.. literalinclude:: /includes/code-examples/Restaurant.cs
:language: csharp
:copyable:
:dedent:
.. literalinclude:: /includes/code-examples/Address.cs
:language: csharp
:copyable:
:dedent:
.. literalinclude:: /includes/code-examples/GradeEntry.cs
:language: csharp
:copyable:
:dedent:
.. include:: /includes/convention-pack-note.rst
.. _csharp-retrieve-find:
Find Documents
--------------
Use the ``Find()`` method to retrieve documents from a collection.
The ``Find()`` method takes a **query filter** and returns all matching documents.
A query filter is an object that specifies the documents you want to retrieve in
your query.
To learn more about query filters, see :ref:`csharp-specify-query`.
.. _csharp-retrieve-find-one:
Find One Document
~~~~~~~~~~~~~~~~~
To find a single document in a collection, pass a query filter that specifies the
criteria of the document you want to find, then chain the ``FirstOrDefault()`` or
``FirstOrDefaultAsync()`` method. If more than one document matches the query
filter, these methods return the *first* matching document from the retrieved
results. If no documents match the query filter the methods return ``null``.
.. tabs::
.. tab:: Asynchronous
:tabid: find-one-async
.. code-block:: csharp
:copyable: true
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
.. tab:: Synchronous
:tabid: find-one-sync
.. code-block:: csharp
:copyable: true
var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
.. tip:: First Document
The ``FirstOrDefault()`` method returns the first document in
:manual:`natural order </reference/glossary/#std-term-natural-order>`
on disk if no sort criteria is specified.
.. To learn more about sorting, see the TODO: sorting page.
To see a full example of using the ``Find()`` method to find a single document, see
:ref:`csharp-retrieve-additional-information`.
.. _csharp-retrieve-find-multiple:
Find Multiple Documents
~~~~~~~~~~~~~~~~~~~~~~~
To find multiple documents in a collection, pass a query filter to the ``Find()``
method that specifies the criteria of the documents you want to retrieve.
You can use a **cursor** to iterate over the documents returned by the ``Find()``
method. A cursor is a mechanism that allows an application to iterate over database
results while holding only a subset of them in memory at a given time. Cursors
are useful when your ``Find()`` method returns a large amount of documents.
To use a cursor to iterate over the documents, pass a
query filter to the ``Find()`` method that specifies the criteria of the documents
you want to find, then chain the ``ToCursor()`` or ``ToCursorAsync()`` method.
To view a synchronous or asynchronous example, select the corresponding tab.
.. tabs::
.. tab:: Asynchronous
:tabid: find-cursor-async
.. code-block:: csharp
:copyable: true
var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync();
.. tab:: Synchronous
:tabid: find-cursor-sync
.. code-block:: csharp
:copyable: true
var restaurants = _restaurantsCollection.Find(filter).ToCursor();
If you are returning a small number of documents, or need your results returned
as a ``List`` object, use the ``ToList()`` or ``ToListAsync()`` methods.
To find multiple documents in a collection and hold them in memory as a list, pass a query filter
to the ``Find()`` method that specifies the criteria of the documents you want
to find, then chain the ``ToList()`` or ``ToListAsync()`` method. To view a
synchronous or asynchronous example, select the corresponding tab.
.. tabs::
.. tab:: Asynchronous
:tabid: find-list-async
.. code-block:: csharp
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();
.. tab:: Synchronous
:tabid: find-list-sync
.. code-block:: csharp
var restaurants = _restaurantsCollection.Find(filter).ToList();
To see a full example of using the ``Find()`` method to find multiple documents,
see :ref:`csharp-retrieve-additional-information`.
.. note:: Find All Documents
To find all documents in a collection, pass an empty filter
to the ``Find()`` method.
.. code-block:: csharp
var filter = Builders<Restaurant>.Filter.Empty;
var allRestaurants = _restaurantsCollection.Find(filter);
To see a fully runnable example of using the ``Find()`` method to find all documents, see
:ref:`csharp-retrieve-additional-information`.
Modify Find Behavior
~~~~~~~~~~~~~~~~~~~~
You can modify the behavior of the ``Find()`` method by passing
a ``FindOptions`` object.
You can configure the commonly used options with the following methods:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Method
- Description
* - ``BatchSize``
- | Gets or sets the maximum number of documents within each
batch returned in a query result. If ``batchSize`` is not set, the ``Find()``
method has an initial batch size of ``101`` documents and a maximum size of 16
mebibytes (MiB) for each subsequent batch. This option can enforce a smaller
limit than 16 MiB, but not a larger one. If you set ``batchSize`` to a limit that
results in batches larger than 16 MiB, this option has no effect and the
``Find()`` method uses the default batch size.
* - ``Collation``
- | Sets the collation options.
* - ``Comment``
- | Sets the comment to the query. To learn more about query comments,
see the :manual:`$comment </reference/operator/query/comment/>` page.
* - ``Hint``
- | Sets the hint for which index to use.
* - ``MaxTime``
- | Sets the maximum execution time on the server for this operation.
To see a full list of available options, see
`FindOptions Properties <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FindOptions.html>`__.
Example
~~~~~~~
This example performs the following actions:
- Finds all documents with "Pizza" in the ``cuisine`` field
- Sets the ``BatchSize`` to ``3``
- Stores the results in a cursor
- Prints the documents referenced by the cursor
.. io-code-block::
:copyable: true
.. input::
:language: csharp
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
var findOptions = new FindOptions { BatchSize = 3 };
using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor())
{
foreach (var r in cursor.ToEnumerable())
{
WriteLine(r.Name);
}
}
.. output::
Pizza Town
Victoria Pizza
...
.. tip:: Clean Up
Create a cursor with a `using statement <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement>`__ to
automatically invoke the
`Dispose() <https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose?view=net-7.0>`__
method once the cursor is no longer in use.
.. _csharp-retrieve-additional-information:
Additional Information
----------------------
To learn more about query filters, see :ref:`csharp-specify-query`.
To learn how to specify queries using LINQ, see :ref:`csharp-linq`.
To view runnable examples of the ``Find()`` method, see the
:ref:`csharp-find-one` page.
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__
- `FirstOrDefault() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IFindFluentExtensions.FirstOrDefault.html>`__
- `FirstOrDefaultAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursorSourceExtensions.FirstOrDefaultAsync.html>`__
- `FindOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FindOptions.html>`__
- `ToList() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursorSourceExtensions.ToList.html>`__
- `ToListAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursorSourceExtensions.FirstOrDefaultAsync.html>`__
- `ToCursor() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursorSource-1.ToCursor.html>`__
- `ToCursorAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursorSource-1.ToCursorAsync.html>`__
.. _csharp-retrieve-instruqt-lab:
.. instruqt:: /mongodb-docs/tracks/find-csharp?token=em_R1T7ZloiDGciGxye
:title: Find() Lesson
:drawer: