|
| 1 | +.. _javars-read-operations: |
| 2 | + |
| 3 | +=============== |
| 4 | +Read Operations |
| 5 | +=============== |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +Read operations retrieve documents or information about documents from a |
| 14 | +collection. You can specify a filter to retrieve only those documents that |
| 15 | +match the filter condition. |
| 16 | + |
| 17 | +Prerequisites |
| 18 | +------------- |
| 19 | + |
| 20 | +You must set up the following components to run the code examples in |
| 21 | +this guide: |
| 22 | + |
| 23 | +- A ``test.restaurants`` collection populated with documents from the |
| 24 | + ``restaurants.json`` file in the `documentation assets GitHub |
| 25 | + <https://raw.githubusercontent.com/mongodb/docs-assets/drivers/restaurants.json>`__. |
| 26 | + |
| 27 | +- The following import statements: |
| 28 | + |
| 29 | +.. code-block:: java |
| 30 | + |
| 31 | + import com.mongodb.*; |
| 32 | + import com.mongodb.reactivestreams.client.MongoClients; |
| 33 | + import com.mongodb.reactivestreams.client.MongoClient; |
| 34 | + import com.mongodb.reactivestreams.client.MongoCollection; |
| 35 | + import com.mongodb.reactivestreams.client.MongoDatabase; |
| 36 | + import com.mongodb.client.model.Projections; |
| 37 | + import com.mongodb.client.model.Filters; |
| 38 | + import com.mongodb.client.model.Sorts; |
| 39 | + |
| 40 | + import java.util.Arrays; |
| 41 | + import org.bson.Document; |
| 42 | + |
| 43 | + import static com.mongodb.client.model.Filters.*; |
| 44 | + import static com.mongodb.client.model.Projections.*; |
| 45 | + |
| 46 | +.. important:: |
| 47 | + |
| 48 | + This guide uses the ``Subscriber`` implementations, which are |
| 49 | + described in the :ref:`Quick Start Primer <javars-primer>`. |
| 50 | + |
| 51 | +Connect to a MongoDB Deployment |
| 52 | +------------------------------- |
| 53 | + |
| 54 | +First, connect to a MongoDB deployment and declare and define |
| 55 | +``MongoDatabase`` and ``MongoCollection`` instances. |
| 56 | + |
| 57 | +The following code connects to a standalone |
| 58 | +MongoDB deployment running on ``localhost`` on port ``27017``. Then, it |
| 59 | +defines the ``database`` variable to refer to the ``test`` database and |
| 60 | +the ``collection`` variable to refer to the ``restaurants`` collection: |
| 61 | + |
| 62 | +.. code-block:: java |
| 63 | + |
| 64 | + MongoClient mongoClient = MongoClients.create(); |
| 65 | + MongoDatabase database = mongoClient.getDatabase("test"); |
| 66 | + MongoCollection<Document> collection = database.getCollection("restaurants"); |
| 67 | + |
| 68 | +To learn more about connecting to MongoDB deployments, |
| 69 | +see the :ref:`javars-connect` tutorial. |
| 70 | + |
| 71 | +Query a Collection |
| 72 | +------------------ |
| 73 | + |
| 74 | +To query the collection, you can use the collection's ``find()`` |
| 75 | +method. |
| 76 | + |
| 77 | +You can call the method without any arguments to query all documents |
| 78 | +in a collection: |
| 79 | + |
| 80 | +.. code-block:: java |
| 81 | + |
| 82 | + collection.find().subscribe(new PrintDocumentSubscriber()); |
| 83 | + |
| 84 | +Or, you can pass a filter to query for documents that match the filter |
| 85 | +criteria: |
| 86 | + |
| 87 | +.. code-block:: java |
| 88 | + |
| 89 | + collection.find(eq("name", "456 Cookies Shop")) |
| 90 | + .subscribe(new PrintDocumentSubscriber()); |
| 91 | + |
| 92 | +Query Filters |
| 93 | +------------- |
| 94 | + |
| 95 | +To query for documents that match certain conditions, pass a filter |
| 96 | +document to the ``find()`` method. |
| 97 | + |
| 98 | +Empty Filter |
| 99 | +~~~~~~~~~~~~ |
| 100 | + |
| 101 | +To specify an empty filter and match all documents in a collection, |
| 102 | +use an empty ``Document`` object: |
| 103 | + |
| 104 | +.. code-block:: java |
| 105 | + |
| 106 | + collection.find(new Document()).subscribe(new PrintDocumentSubscriber()); |
| 107 | + |
| 108 | +.. tip:: |
| 109 | + |
| 110 | + When using the ``find()`` method, you can also call the method without |
| 111 | + passing any filter object to match all documents in a collection. |
| 112 | + |
| 113 | + .. code-block:: java |
| 114 | + |
| 115 | + collection.find().subscribe(new PrintDocumentSubscriber()); |
| 116 | + |
| 117 | +Filters Helper |
| 118 | +~~~~~~~~~~~~~~ |
| 119 | + |
| 120 | +To facilitate the creation of filter documents, the driver |
| 121 | +provides the ``Filters`` class that provides filter condition helper |
| 122 | +methods. |
| 123 | + |
| 124 | +This example find operation includes a filter |
| 125 | +``Document`` instance which specifies the following conditions: |
| 126 | + |
| 127 | +- ``stars`` field value is greater than or equal to ``2`` and less than ``5`` |
| 128 | +- ``categories`` field equals ``"Bakery"``, or if ``categories`` is an |
| 129 | + array field, contains the string ``"Bakery"`` as an element |
| 130 | + |
| 131 | +.. code-block:: java |
| 132 | + |
| 133 | + collection.find( |
| 134 | + new Document("stars", new Document("$gte", 2) |
| 135 | + .append("$lt", 5)) |
| 136 | + .append("categories", "Bakery")).subscribe(new PrintDocumentSubscriber()); |
| 137 | + |
| 138 | +The following example specifies the same filter condition using the |
| 139 | +``Filters`` helper methods: |
| 140 | + |
| 141 | +.. code-block:: java |
| 142 | + |
| 143 | + collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) |
| 144 | + .subscribe(new PrintDocumentSubscriber()); |
| 145 | + |
| 146 | +To view a list of query filter operators, see :manual:`Query and |
| 147 | +Projection Operators </reference/operator/query/>` in the |
| 148 | +Server manual. To view a list of ``Filters`` helpers, see the `Filters |
| 149 | +API documentation <{+api+}/mongodb-driver-core/com/mongodb/client/model/Filters.html>`__. |
| 150 | + |
| 151 | +FindPublisher |
| 152 | +------------- |
| 153 | + |
| 154 | +The ``find()`` method returns an instance of the ``FindPublisher`` |
| 155 | +interface. The interface provides various methods that you can chain |
| 156 | +to the ``find()`` method to modify the output or behavior of the query, |
| 157 | +such as ``sort()`` or ``projection()``, as well as for iterating |
| 158 | +the results via the ``subscribe()`` method. |
| 159 | + |
| 160 | +Projections |
| 161 | +~~~~~~~~~~~ |
| 162 | + |
| 163 | +By default, queries in MongoDB return all fields in matching |
| 164 | +documents. To specify the fields to return in the matching documents, |
| 165 | +you can specify a projection document. |
| 166 | + |
| 167 | +This find operation example includes a projection |
| 168 | +``Document`` which specifies that the matching documents include only the |
| 169 | +``name``, ``stars``, and the ``categories`` fields: |
| 170 | + |
| 171 | +.. code-block:: java |
| 172 | + |
| 173 | + collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) |
| 174 | + .projection(new Document("name", 1) |
| 175 | + .append("stars", 1) |
| 176 | + .append("categories",1) |
| 177 | + .append("_id", 0)) |
| 178 | + .subscribe(new PrintDocumentSubscriber()); |
| 179 | + |
| 180 | +To facilitate the creation of projection documents, the driver |
| 181 | +provides the ``Projections`` class. |
| 182 | + |
| 183 | +.. code-block:: java |
| 184 | + |
| 185 | + collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) |
| 186 | + .projection(fields(include("name", "stars", "categories"), excludeId())) |
| 187 | + .subscribe(new PrintDocumentSubscriber()); |
| 188 | + |
| 189 | +In the projection document, you can also specify a projection |
| 190 | +expression by using a projection operator. |
| 191 | + |
| 192 | +.. TODO update link To view an example that uses the ``Projections.metaTextScore()`` method, see the |
| 193 | +.. :ref:`Text Search <>` tutorial. |
| 194 | + |
| 195 | +Sorts |
| 196 | +~~~~~ |
| 197 | + |
| 198 | +To sort documents, pass a sort specification document to the |
| 199 | +``FindPublisher.sort()`` method. The driver provides ``Sorts`` |
| 200 | +helper methods to facilitate the creation of the sort specification document. |
| 201 | + |
| 202 | +.. code-block:: java |
| 203 | + |
| 204 | + collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) |
| 205 | + .sort(Sorts.ascending("name")) |
| 206 | + .subscribe(new PrintDocumentSubscriber()); |
| 207 | + |
| 208 | +Sort with Projections |
| 209 | +~~~~~~~~~~~~~~~~~~~~~ |
| 210 | + |
| 211 | +The ``FindPublisher`` methods themselves return ``FindPublisher`` |
| 212 | +objects, and as such, you can append multiple ``FindPublisher`` methods |
| 213 | +to the ``find()`` method: |
| 214 | + |
| 215 | +.. code-block:: java |
| 216 | + |
| 217 | + collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) |
| 218 | + .sort(Sorts.ascending("name")) |
| 219 | + .projection(fields(include("name", "stars", "categories"), excludeId())) |
| 220 | + .subscribe(new PrintDocumentSubscriber()); |
| 221 | + |
| 222 | +Explain |
| 223 | +~~~~~~~ |
| 224 | + |
| 225 | +To explain a find operation, call the ``FindPublisher.explain()`` |
| 226 | +method: |
| 227 | + |
| 228 | +.. code-block:: java |
| 229 | + |
| 230 | + collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories", "Bakery"))) |
| 231 | + .explain() |
| 232 | + .subscribe(new PrintDocumentSubscriber()); |
| 233 | + |
| 234 | +Read Preference |
| 235 | +--------------- |
| 236 | + |
| 237 | +For read operations on replica sets or sharded clusters, |
| 238 | +you can configure the read preference at the following levels: |
| 239 | + |
| 240 | +- In a ``MongoClient`` in the following ways: |
| 241 | + |
| 242 | + - By creating a ``MongoClientSettings`` instance: |
| 243 | + |
| 244 | + .. code-block:: java |
| 245 | + |
| 246 | + MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder() |
| 247 | + .applyConnectionString(new ConnectionString("mongodb://host1,host2")) |
| 248 | + .readPreference(ReadPreference.secondary()) |
| 249 | + .build()); |
| 250 | + |
| 251 | + - By creating a ``ConnectionString`` instance: |
| 252 | + |
| 253 | + .. code-block:: java |
| 254 | + |
| 255 | + MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readPreference=secondary"); |
| 256 | + |
| 257 | +- In a ``MongoDatabase`` by using the ``withReadPreference()`` method: |
| 258 | + |
| 259 | + .. code-block:: java |
| 260 | + |
| 261 | + MongoDatabase database = mongoClient.getDatabase("test") |
| 262 | + .withReadPreference(ReadPreference.secondary()); |
| 263 | + |
| 264 | +- In a ``MongoCollection`` by using the ``withReadPreference()`` method: |
| 265 | + |
| 266 | + .. code-block:: java |
| 267 | + |
| 268 | + MongoCollection<Document> collection = database.getCollection("restaurants") |
| 269 | + .withReadPreference(ReadPreference.secondary()); |
| 270 | + |
| 271 | +``MongoDatabase`` and ``MongoCollection`` instances are immutable. Calling |
| 272 | +``withReadPreference()`` on an existing ``MongoDatabase`` or |
| 273 | +``MongoCollection`` instance returns a new instance and does not affect |
| 274 | +the instance on which the method is called. |
| 275 | + |
| 276 | +In the following example, the ``collectionWithReadPref`` instance |
| 277 | +has the read preference of ``primaryPreferred`` whereas the read |
| 278 | +preference of the ``collection`` is unaffected: |
| 279 | + |
| 280 | +.. code-block:: java |
| 281 | + |
| 282 | + MongoCollection<Document> collectionWithReadPref = collection.withReadPreference(ReadPreference.primaryPreferred()); |
| 283 | + |
| 284 | +Read Concern |
| 285 | +------------ |
| 286 | + |
| 287 | +For read operations on replica sets or sharded clusters, |
| 288 | +applications can configure the read concern at the following levels: |
| 289 | + |
| 290 | +- In a ``MongoClient`` in the following ways: |
| 291 | + |
| 292 | + - By creating a ``MongoClientSettings`` instance: |
| 293 | + |
| 294 | + .. code-block:: java |
| 295 | + |
| 296 | + MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder() |
| 297 | + .applyConnectionString(new ConnectionString("mongodb://host1,host2")) |
| 298 | + .readConcern(ReadConcern.MAJORITY) |
| 299 | + .build()); |
| 300 | + |
| 301 | + - By creating a ``ConnectionString`` instance: |
| 302 | + |
| 303 | + .. code-block:: java |
| 304 | + |
| 305 | + MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?readConcernLevel=majority"); |
| 306 | + |
| 307 | +- In a ``MongoDatabase`` by using the ``withReadConcern()`` method: |
| 308 | + |
| 309 | + .. code-block:: java |
| 310 | + |
| 311 | + MongoDatabase database = mongoClient.getDatabase("test") |
| 312 | + .withReadConcern(ReadConcern.MAJORITY); |
| 313 | + |
| 314 | +- In a ``MongoCollection`` by using the ``withReadConcern()`` method: |
| 315 | + |
| 316 | + .. code-block:: java |
| 317 | + |
| 318 | + MongoCollection<Document> collection = database.getCollection("restaurants") |
| 319 | + .withReadConcern(ReadConcern.MAJORITY); |
| 320 | + |
| 321 | +``MongoDatabase`` and ``MongoCollection`` instances are immutable. Calling |
| 322 | +``withReadConcern()`` on an existing ``MongoDatabase`` or |
| 323 | +``MongoCollection`` instance returns a new instance and does not affect |
| 324 | +the instance on which the method is called. |
| 325 | + |
| 326 | +In the following example, the ``collWithReadConcern`` instance has |
| 327 | +an ``AVAILABLE`` read concern whereas the read concern of the ``collection`` |
| 328 | +is unaffected: |
| 329 | + |
| 330 | +.. code-block:: java |
| 331 | + |
| 332 | + MongoCollection<Document> collWithReadConcern = collection.withReadConcern(ReadConcern.AVAILABLE); |
| 333 | + |
| 334 | +You can build ``MongoClientSettings``, ``MongoDatabase``, or |
| 335 | +``MongoCollection`` instances to include combinations of read concerns, read |
| 336 | +preferences, and write concerns. |
| 337 | + |
| 338 | +For example, the following code sets all three at the collection level: |
| 339 | + |
| 340 | +.. code-block:: java |
| 341 | + |
| 342 | + collection = database.getCollection("restaurants") |
| 343 | + .withReadPreference(ReadPreference.primary()) |
| 344 | + .withReadConcern(ReadConcern.MAJORITY) |
| 345 | + .withWriteConcern(WriteConcern.MAJORITY); |
0 commit comments