|
| 1 | +.. _charp-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/Retrieve.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 | +Find One Document |
| 48 | +~~~~~~~~~~~~~~~~~ |
| 49 | + |
| 50 | +To find a single document in a collection, pass a query filter that specifies the |
| 51 | +criteria of the document you want to find, then chain the ``FirstOrDefault()`` or |
| 52 | +``FirstOrDefaultAsync()`` method. If more than one document matches the query |
| 53 | +filter, these methods return the *first* matching document from the retrieved |
| 54 | +results. If no documents match the query filter the methods return ``null``. |
| 55 | + |
| 56 | +.. tabs:: |
| 57 | + |
| 58 | + .. tab:: Asynchronous |
| 59 | + :tabid: find-one-async |
| 60 | + |
| 61 | + .. code-block:: csharp |
| 62 | + :copyable: true |
| 63 | + |
| 64 | + var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync(); |
| 65 | + |
| 66 | + .. tab:: Synchronous |
| 67 | + :tabid: find-one-sync |
| 68 | + |
| 69 | + .. code-block:: csharp |
| 70 | + :copyable: true |
| 71 | + |
| 72 | + var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault(); |
| 73 | + |
| 74 | +.. tip:: First Document |
| 75 | + |
| 76 | + The ``FirstOrDefault()`` method returns the first document in |
| 77 | + :manual:`natural order </reference/glossary/#std-term-natural-order>` |
| 78 | + on disk if no sort criteria is specified. |
| 79 | + |
| 80 | + To learn more about sorting, see the TODO: sorting page. |
| 81 | + |
| 82 | +To see a full example of using the ``Find()`` method to find a single document, see |
| 83 | +:ref:`csharp-retrieve-additional-information`. |
| 84 | + |
| 85 | +Find Multiple Documents |
| 86 | +~~~~~~~~~~~~~~~~~~~~~~~ |
| 87 | + |
| 88 | +To find multiple documents in a collection, pass a query filter to the ``Find()`` |
| 89 | +method that specifies the criteria of the documents you want to retrieve. |
| 90 | + |
| 91 | +You can use a **cursor** to iterate over the documents returned by the ``Find()`` |
| 92 | +method. A cursor is a mechanism that allows an application to iterate over database |
| 93 | +results while holding only a subset of them in memory at a given time. Cursors |
| 94 | +are useful when your ``Find()`` method returns a large amount of documents. |
| 95 | + |
| 96 | +To use a cursor to iterate over the documents, pass a |
| 97 | +query filter to the ``Find()`` method that specifies the criteria of the documents |
| 98 | +you want to find, then chain the ``ToCursor()`` or ``ToCursorAsync()`` method. |
| 99 | +To view a synchronous or asynchronous example, select the corresponding tab. |
| 100 | + |
| 101 | +.. tabs:: |
| 102 | + |
| 103 | + .. tab:: Asynchronous |
| 104 | + :tabid: find-cursor-async |
| 105 | + |
| 106 | + .. code-block:: csharp |
| 107 | + :copyable: true |
| 108 | + |
| 109 | + var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync(); |
| 110 | + |
| 111 | + .. tab:: Synchronous |
| 112 | + :tabid: find-cursor-sync |
| 113 | + |
| 114 | + .. code-block:: csharp |
| 115 | + :copyable: true |
| 116 | + |
| 117 | + var restaurants = _restaurantsCollection.Find(filter).ToCursor(); |
| 118 | + |
| 119 | +If you are returning a small number of documents, or need your results returned |
| 120 | +as a ``List`` object, use the ``ToList()`` or ``ToListAsync()`` methods. |
| 121 | + |
| 122 | +To find multiple documents in a collection and hold them in memory as a list, pass a query filter |
| 123 | +to the ``Find()`` method that specifies the criteria of the documents you want |
| 124 | +to find, then chain the ``ToList()`` or ``ToListAsync()`` method.To view a |
| 125 | +synchronous or asynchronous example, select the corresponding tab. |
| 126 | + |
| 127 | +.. tabs:: |
| 128 | + |
| 129 | + .. tab:: Asynchronous |
| 130 | + :tabid: find-list-async |
| 131 | + |
| 132 | + .. code-block:: csharp |
| 133 | + |
| 134 | + var restaurants = await _restaurantsCollection.Find(filter).ToList(); |
| 135 | + |
| 136 | + .. tab:: Synchronous |
| 137 | + :tabid: find-list-sync |
| 138 | + |
| 139 | + .. code-block:: csharp |
| 140 | + |
| 141 | + var restaurants = _restaurantsCollection.Find(filter).ToListAsync(); |
| 142 | + |
| 143 | +To see a full example of using the ``Find()`` method to find multiple documents, |
| 144 | +see :ref:`csharp-retrieve-additional-information`. |
| 145 | + |
| 146 | +.. note:: Find All Documents |
| 147 | + |
| 148 | + To find all documents in a collection, pass an empty ``BsonDocument`` as a |
| 149 | + query filter to the ``Find()`` method. |
| 150 | + |
| 151 | + To see a fully runnable example of using the ``Find()`` method to find all documents, see |
| 152 | + :ref:`csharp-retrieve-additional-information`. |
| 153 | + |
| 154 | +Modify Find Behavior |
| 155 | +~~~~~~~~~~~~~~~~~~~~ |
| 156 | + |
| 157 | +You can modify the behavior of the ``Find()`` method by passing |
| 158 | +a ``FindOptions`` object. |
| 159 | + |
| 160 | +You can configure the commonly used options with the following methods: |
| 161 | + |
| 162 | +.. list-table:: |
| 163 | + :widths: 30 70 |
| 164 | + :header-rows: 1 |
| 165 | + |
| 166 | + * - Method |
| 167 | + - Description |
| 168 | + |
| 169 | + * - ``BatchSize`` |
| 170 | + - | Gets or sets the number of documents to hold in a cursor at a given time. |
| 171 | + |
| 172 | + * - ``Collation`` |
| 173 | + - | Sets the collation options. |
| 174 | + |
| 175 | + * - ``Comment`` |
| 176 | + - | Sets the comment to the query. To learn more about query comments, |
| 177 | + see the :manual:`$comment </reference/operator/query/comment/>` page. |
| 178 | + |
| 179 | + * - ``Hint`` |
| 180 | + - | Sets the hint for which index to use. |
| 181 | + |
| 182 | + * - ``MaxTime`` |
| 183 | + - | Sets the maximum execution time on the server for this operation. |
| 184 | + |
| 185 | +To see a full list of available options, see |
| 186 | +`FindOptions Properties <{+api-root+}/Properties_T_MongoDB_Driver_FindOptions.htm>`__. |
| 187 | + |
| 188 | +Example |
| 189 | +~~~~~~~ |
| 190 | + |
| 191 | +The following example performs these actions: |
| 192 | + |
| 193 | +- Finds all documents with "Pizza" in the ``cuisine`` field |
| 194 | +- Sets the ``BatchSize`` to ``3`` |
| 195 | +- Stores the results in a cursor |
| 196 | +- Prints the number of documents currently held in the cursor |
| 197 | + |
| 198 | +.. io-code-block:: |
| 199 | + :copyable: true |
| 200 | + |
| 201 | + .. input:: |
| 202 | + :language: csharp |
| 203 | + |
| 204 | + var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza"); |
| 205 | + |
| 206 | + var findOptions = new FindOptions |
| 207 | + { |
| 208 | + BatchSize = 3 |
| 209 | + }; |
| 210 | + |
| 211 | + using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor()) |
| 212 | + { |
| 213 | + cursor.MoveNext(); |
| 214 | + WriteLine($"Number of documents in cursor: {cursor.Current.Count()}"); |
| 215 | + } |
| 216 | + |
| 217 | + .. output:: |
| 218 | + |
| 219 | + Number of documents in cursor: 3 |
| 220 | + |
| 221 | +.. tip:: Clean Up |
| 222 | + |
| 223 | + Create a cursor with a `using statement <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement>`__ to |
| 224 | + automatically invoke the |
| 225 | + `Dispose() <https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose?view=net-7.0>`__ |
| 226 | + method once the cursor is no longer in use. |
| 227 | + |
| 228 | + |
| 229 | +.. _csharp-retrieve-additional-information: |
| 230 | + |
| 231 | +Additional Information |
| 232 | +---------------------- |
| 233 | + |
| 234 | +.. TODO: Links to creating filter with Builders and LINQ |
| 235 | + |
| 236 | +To learn more about query filters, see :ref:`csharp-specify-query` |
| 237 | + |
| 238 | +To view runnable examples of the ``Find()`` method, see the |
| 239 | +:ref:`csharp-find-one` page. |
| 240 | + |
| 241 | +API Documentation |
| 242 | +~~~~~~~~~~~~~~~~~ |
| 243 | + |
| 244 | +To learn more about any of the methods or types discussed in this |
| 245 | +guide, see the following API Documentation: |
| 246 | + |
| 247 | +- `Find() <{+api-root+}/Overload_MongoDB_Driver_IMongoCollectionExtensions_Find.htm>`__ |
| 248 | +- `FirstOrDefault() <{+api-root+}/M_MongoDB_Driver_IFindFluentExtensions_FirstOrDefault__2.htm>`__ |
| 249 | +- `FirstOrDefaultAsync() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSourceExtensions_FirstOrDefaultAsync__1.htm>`__ |
| 250 | +- `FindOptions <{+api-root+}/T_MongoDB_Driver_FindOptions.htm>`__ |
| 251 | +- `ToList() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSourceExtensions_ToList__1.htm>`__ |
| 252 | +- `ToListAsync() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSourceExtensions_ToListAsync__1.htm>`__ |
| 253 | +- `ToCursor() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSource_1_ToCursor.htm>`__ |
| 254 | +- `ToCursorAsync() <{+api-root+}/M_MongoDB_Driver_IAsyncCursorSource_1_ToCursorAsync.htm>`__ |
0 commit comments