Skip to content

Commit 483e70d

Browse files
CRUD (#53)
1 parent 7f376fd commit 483e70d

23 files changed

+1994
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
.. _csharp-crud-read-operations:
2+
3+
===============
4+
Read Operations
5+
===============
6+
7+
.. toctree::
8+
:caption: Read Operations
9+
10+
/fundamentals/crud/read-operations/retrieve
11+
/fundamentals/crud/read-operations/specify-query
12+
13+
- :ref:`csharp-retrieve`
14+
- :ref:`csharp-specify-query`
Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
.. _csharp-retrieve:
2+
3+
=============
4+
Retrieve Data
5+
=============
6+
7+
.. default-domain:: mongodb
8+
9+
.. contents:: On this page
10+
:local:
11+
:backlinks: none
12+
:depth: 2
13+
:class: singlecol
14+
15+
Overview
16+
--------
17+
18+
In this guide, you can learn how to retrieve data from your MongoDB
19+
collections with the {+driver-long+}.
20+
21+
Sample Data
22+
~~~~~~~~~~~
23+
24+
The examples in this guide use the ``sample_restaurants.restaurants`` collection
25+
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
26+
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`.
27+
28+
The following ``Restaurants`` class models the documents in this collection:
29+
30+
.. literalinclude:: ../../../includes/fundamentals/code-examples/crud/Restaurant.cs
31+
:language: csharp
32+
:copyable:
33+
:dedent:
34+
35+
.. _csharp-retrieve-find:
36+
37+
Find Documents
38+
--------------
39+
40+
Use the ``Find()`` method to retrieve documents from a collection.
41+
The ``Find()`` method takes a **query filter** and returns all matching documents.
42+
A query filter is an object that specifies the documents you want to retrieve in
43+
your query.
44+
45+
To learn more about query filters, see :ref:`csharp-specify-query`.
46+
47+
.. _csharp-retrieve-find-one:
48+
49+
Find One Document
50+
~~~~~~~~~~~~~~~~~
51+
52+
To find a single document in a collection, pass a query filter that specifies the
53+
criteria of the document you want to find, then chain the ``FirstOrDefault()`` or
54+
``FirstOrDefaultAsync()`` method. If more than one document matches the query
55+
filter, these methods return the *first* matching document from the retrieved
56+
results. If no documents match the query filter the methods return ``null``.
57+
58+
.. tabs::
59+
60+
.. tab:: Asynchronous
61+
:tabid: find-one-async
62+
63+
.. code-block:: csharp
64+
:copyable: true
65+
66+
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
67+
68+
.. tab:: Synchronous
69+
:tabid: find-one-sync
70+
71+
.. code-block:: csharp
72+
:copyable: true
73+
74+
var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
75+
76+
.. tip:: First Document
77+
78+
The ``FirstOrDefault()`` method returns the first document in
79+
:manual:`natural order </reference/glossary/#std-term-natural-order>`
80+
on disk if no sort criteria is specified.
81+
82+
.. To learn more about sorting, see the TODO: sorting page.
83+
84+
To see a full example of using the ``Find()`` method to find a single document, see
85+
:ref:`csharp-retrieve-additional-information`.
86+
87+
.. _csharp-retrieve-find-multiple:
88+
89+
Find Multiple Documents
90+
~~~~~~~~~~~~~~~~~~~~~~~
91+
92+
To find multiple documents in a collection, pass a query filter to the ``Find()``
93+
method that specifies the criteria of the documents you want to retrieve.
94+
95+
You can use a **cursor** to iterate over the documents returned by the ``Find()``
96+
method. A cursor is a mechanism that allows an application to iterate over database
97+
results while holding only a subset of them in memory at a given time. Cursors
98+
are useful when your ``Find()`` method returns a large amount of documents.
99+
100+
To use a cursor to iterate over the documents, pass a
101+
query filter to the ``Find()`` method that specifies the criteria of the documents
102+
you want to find, then chain the ``ToCursor()`` or ``ToCursorAsync()`` method.
103+
To view a synchronous or asynchronous example, select the corresponding tab.
104+
105+
.. tabs::
106+
107+
.. tab:: Asynchronous
108+
:tabid: find-cursor-async
109+
110+
.. code-block:: csharp
111+
:copyable: true
112+
113+
var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync();
114+
115+
.. tab:: Synchronous
116+
:tabid: find-cursor-sync
117+
118+
.. code-block:: csharp
119+
:copyable: true
120+
121+
var restaurants = _restaurantsCollection.Find(filter).ToCursor();
122+
123+
If you are returning a small number of documents, or need your results returned
124+
as a ``List`` object, use the ``ToList()`` or ``ToListAsync()`` methods.
125+
126+
To find multiple documents in a collection and hold them in memory as a list, pass a query filter
127+
to the ``Find()`` method that specifies the criteria of the documents you want
128+
to find, then chain the ``ToList()`` or ``ToListAsync()`` method. To view a
129+
synchronous or asynchronous example, select the corresponding tab.
130+
131+
.. tabs::
132+
133+
.. tab:: Asynchronous
134+
:tabid: find-list-async
135+
136+
.. code-block:: csharp
137+
138+
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();
139+
140+
.. tab:: Synchronous
141+
:tabid: find-list-sync
142+
143+
.. code-block:: csharp
144+
145+
var restaurants = _restaurantsCollection.Find(filter).ToList();
146+
147+
To see a full example of using the ``Find()`` method to find multiple documents,
148+
see :ref:`csharp-retrieve-additional-information`.
149+
150+
.. note:: Find All Documents
151+
152+
To find all documents in a collection, pass an empty filter
153+
to the ``Find()`` method.
154+
155+
.. code-block:: csharp
156+
157+
var filter = Builders<Restaurant>.Filter.Empty;
158+
var allRestaurants = _restaurantsCollection.Find(filter);
159+
160+
To see a fully runnable example of using the ``Find()`` method to find all documents, see
161+
:ref:`csharp-retrieve-additional-information`.
162+
163+
Modify Find Behavior
164+
~~~~~~~~~~~~~~~~~~~~
165+
166+
You can modify the behavior of the ``Find()`` method by passing
167+
a ``FindOptions`` object.
168+
169+
You can configure the commonly used options with the following methods:
170+
171+
.. list-table::
172+
:widths: 30 70
173+
:header-rows: 1
174+
175+
* - Method
176+
- Description
177+
178+
* - ``BatchSize``
179+
- | Gets or sets the number of documents to hold in a cursor at a given time.
180+
181+
* - ``Collation``
182+
- | Sets the collation options.
183+
184+
* - ``Comment``
185+
- | Sets the comment to the query. To learn more about query comments,
186+
see the :manual:`$comment </reference/operator/query/comment/>` page.
187+
188+
* - ``Hint``
189+
- | Sets the hint for which index to use.
190+
191+
* - ``MaxTime``
192+
- | Sets the maximum execution time on the server for this operation.
193+
194+
To see a full list of available options, see
195+
`FindOptions Properties <{+api-root+}/Properties_T_MongoDB_Driver_FindOptions.htm>`__.
196+
197+
Example
198+
~~~~~~~
199+
200+
The following example performs these actions:
201+
202+
- Finds all documents with "Pizza" in the ``cuisine`` field
203+
- Sets the ``BatchSize`` to ``3``
204+
- Stores the results in a cursor
205+
- Prints the number of documents currently held in the cursor
206+
207+
.. io-code-block::
208+
:copyable: true
209+
210+
.. input::
211+
:language: csharp
212+
213+
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
214+
215+
var findOptions = new FindOptions
216+
{
217+
BatchSize = 3
218+
};
219+
220+
using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor())
221+
{
222+
cursor.MoveNext();
223+
Console.WriteLine($"Number of documents in cursor: {cursor.Current.Count()}");
224+
}
225+
226+
.. output::
227+
228+
Number of documents in cursor: 3
229+
230+
.. tip:: Clean Up
231+
232+
Create a cursor with a `using statement <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement>`__ to
233+
automatically invoke the
234+
`Dispose() <https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose?view=net-7.0>`__
235+
method once the cursor is no longer in use.
236+
237+
238+
.. _csharp-retrieve-additional-information:
239+
240+
Additional Information
241+
----------------------
242+
243+
To learn more about query filters, see :ref:`csharp-specify-query`.
244+
245+
To learn how to specify queries using LINQ, see :ref:`csharp-linq`.
246+
247+
To view runnable examples of the ``Find()`` method, see the
248+
:ref:`csharp-find-one` page.
249+
250+
API Documentation
251+
~~~~~~~~~~~~~~~~~
252+
253+
To learn more about any of the methods or types discussed in this
254+
guide, see the following API Documentation:
255+
256+
- `Find() <{+api-root+}/Overload_MongoDB_Driver_IMongoCollectionExtensions_Find.htm>`__
257+
- `FirstOrDefault() <{+api-root+}/M_MongoDB_Driver_IFindFluentExtensions_FirstOrDefault__2.htm>`__
258+
- `FirstOrDefaultAsync() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSourceExtensions_FirstOrDefaultAsync__1.htm>`__
259+
- `FindOptions <{+api-root+}/T_MongoDB_Driver_FindOptions.htm>`__
260+
- `ToList() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSourceExtensions_ToList__1.htm>`__
261+
- `ToListAsync() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSourceExtensions_ToListAsync__1.htm>`__
262+
- `ToCursor() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSource_1_ToCursor.htm>`__
263+
- `ToCursorAsync() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSource_1_ToCursorAsync.htm>`__

0 commit comments

Comments
 (0)