|
| 1 | +.. _javars-pojo-qs: |
| 2 | + |
| 3 | +=========================== |
| 4 | +Quick Start (POJO Examples) |
| 5 | +=========================== |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +This guide is similar to the :ref:`Quick Start guide |
| 14 | +<javars-quickstart>` but uses Plain Old Java Objects, or POJOs, to |
| 15 | +model documents instead of the generic ``Document`` class. |
| 16 | + |
| 17 | +The code examples in this guide come from the `PojoQuickTour.java |
| 18 | +<{+driver-source-gh+}/blob/master/driver-reactive-streams/src/examples/reactivestreams/tour/PojoQuickTour.java>`__ |
| 19 | +file in the driver source code GitHub repository. |
| 20 | + |
| 21 | +.. important:: |
| 22 | + |
| 23 | + This guide uses the ``Subscriber`` implementations, which are |
| 24 | + described in the :ref:`Quick Start Primer <javars-primer>`. |
| 25 | + |
| 26 | +Prerequisites |
| 27 | +------------- |
| 28 | + |
| 29 | +You must set up the following components to run the code examples in |
| 30 | +this guide: |
| 31 | + |
| 32 | +- MongoDB server running on the default port for MongoDB (``27017``) |
| 33 | +- Driver dependency installed in your project |
| 34 | +- The following import statements: |
| 35 | + |
| 36 | +.. code-block:: java |
| 37 | + |
| 38 | + import com.mongodb.client.result.InsertOneResult; |
| 39 | + import com.mongodb.client.result.InsertManyResult; |
| 40 | + import com.mongodb.client.result.DeleteResult; |
| 41 | + import com.mongodb.client.result.UpdateResult; |
| 42 | + import com.mongodb.reactivestreams.client.MongoClient; |
| 43 | + import com.mongodb.reactivestreams.client.MongoClients; |
| 44 | + import com.mongodb.reactivestreams.client.MongoCollection; |
| 45 | + import com.mongodb.reactivestreams.client.MongoDatabase; |
| 46 | + |
| 47 | + import org.bson.codecs.configuration.CodecRegistry; |
| 48 | + import org.bson.codecs.pojo.PojoCodecProvider; |
| 49 | + |
| 50 | + import java.util.List; |
| 51 | + |
| 52 | + import static com.mongodb.client.model.Filters.*; |
| 53 | + import static com.mongodb.client.model.Updates.*; |
| 54 | + import static java.util.Arrays.asList; |
| 55 | + import static org.bson.codecs.configuration.CodecRegistries.fromProviders; |
| 56 | + import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; |
| 57 | + |
| 58 | +- POJO class definitions. Copy the full code for the ``Person`` and |
| 59 | + ``Address`` POJOs from the driver source repository on |
| 60 | + GitHub: |
| 61 | + |
| 62 | + - `Person class <{+driver-source-gh+}/blob/master/driver-reactive-streams/src/examples/reactivestreams/tour/Person.java>`__ |
| 63 | + - `Address class <{+driver-source-gh+}/blob/master/driver-reactive-streams/src/examples/reactivestreams/tour/Address.java>`__ |
| 64 | + |
| 65 | +Creating a Custom CodecRegistry |
| 66 | +------------------------------- |
| 67 | + |
| 68 | +Before you can use a POJO with the driver, you need to configure the |
| 69 | +``CodecRegistry`` to include a codec that handles the translation to and |
| 70 | +from BSON for your POJOs. The simplest way to do that is to use |
| 71 | +the ``PojoCodecProvider.builder()`` method to create and configure a |
| 72 | +``CodecProvider``. |
| 73 | + |
| 74 | +The following example combines the default codec registry with |
| 75 | +the ``PojoCodecProvider`` configured to automatically create POJO |
| 76 | +``Codec`` instances: |
| 77 | + |
| 78 | +.. code-block:: java |
| 79 | + |
| 80 | + CodecRegistry pojoCodecRegistry = fromRegistries( |
| 81 | + MongoClientSettings.getDefaultCodecRegistry(), |
| 82 | + fromProviders(PojoCodecProvider.builder().automatic(true).build()) |
| 83 | + ); |
| 84 | + |
| 85 | +.. note:: |
| 86 | + |
| 87 | + The registries are checked in order until one returns a codec for the |
| 88 | + requested class. The ``DefaultCodecRegistry`` should be first in the |
| 89 | + list, and the ``PojoCodecProvider`` should always be the last |
| 90 | + ``CodecProvider`` since it can provide a codec for almost any class. |
| 91 | + |
| 92 | +Using the CodecRegistry |
| 93 | +~~~~~~~~~~~~~~~~~~~~~~~ |
| 94 | + |
| 95 | +The following list describes ways to set the ``pojoCodecRegistry`` for |
| 96 | +use: |
| 97 | + |
| 98 | +- Set it when instantiating a ``MongoClient`` object: |
| 99 | + |
| 100 | + .. code-block:: java |
| 101 | + |
| 102 | + MongoClientSettings settings = MongoClientSettings.builder() |
| 103 | + .codecRegistry(pojoCodecRegistry) |
| 104 | + .build(); |
| 105 | + MongoClient mongoClient = MongoClients.create(settings); |
| 106 | + |
| 107 | +- Use an alternative ``CodecRegistry`` with a ``MongoDatabase``: |
| 108 | + |
| 109 | + .. code-block:: java |
| 110 | + |
| 111 | + database = database.withCodecRegistry(pojoCodecRegistry); |
| 112 | + |
| 113 | +- Use an alternative ``CodecRegistry`` with a ``MongoCollection``: |
| 114 | + |
| 115 | + .. code-block:: java |
| 116 | + |
| 117 | + collection = collection.withCodecRegistry(pojoCodecRegistry); |
| 118 | + |
| 119 | +Inserting a POJO into MongoDB |
| 120 | +----------------------------- |
| 121 | + |
| 122 | +The codec registry automatically tries to create a POJO ``Codec`` for |
| 123 | +unknown classes. This allows you to use POJOs out of the box without |
| 124 | +any extra configuration. |
| 125 | + |
| 126 | +Before you can insert a POJO into MongoDB, create a |
| 127 | +``MongoCollection`` instance configured with the POJO class: |
| 128 | + |
| 129 | +.. code-block:: java |
| 130 | + |
| 131 | + MongoCollection<Person> collection = database.getCollection("people", Person.class); |
| 132 | + |
| 133 | +Insert a Person Instance |
| 134 | +~~~~~~~~~~~~~~~~~~~~~~~~ |
| 135 | + |
| 136 | +.. _javars-pojo-insertone: |
| 137 | + |
| 138 | +To insert a ``Person`` into the collection, use the collection's |
| 139 | +``insertOne()`` method: |
| 140 | + |
| 141 | +.. code-block:: java |
| 142 | + |
| 143 | + Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1")); |
| 144 | + collection.insertOne(ada).subscribe(new OperationSubscriber<InsertOneResult>()); |
| 145 | + |
| 146 | +Insert Multiple Person Instances |
| 147 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 148 | + |
| 149 | +To insert multiple ``Person`` instances, you can use the collection's |
| 150 | +``insertMany()`` method, which takes a list of ``Person`` instances as a |
| 151 | +parameter. |
| 152 | + |
| 153 | +The following example will add multiple ``Person`` instances into the |
| 154 | +collection: |
| 155 | + |
| 156 | +.. code-block:: java |
| 157 | + |
| 158 | + List<Person> people = asList( |
| 159 | + new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), |
| 160 | + new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), |
| 161 | + new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)) |
| 162 | + ); |
| 163 | + collection.insertMany(people).subscribe(new OperationSubscriber<InsertManyResult>()); |
| 164 | + |
| 165 | +Query the Collection |
| 166 | +-------------------- |
| 167 | + |
| 168 | +To query the collection, you can use the ``find()`` method. |
| 169 | + |
| 170 | +The following example prints all the ``Person`` instances in the |
| 171 | +collection: |
| 172 | + |
| 173 | +.. io-code-block:: |
| 174 | + :copyable: true |
| 175 | + |
| 176 | + .. input:: |
| 177 | + :language: java |
| 178 | + |
| 179 | + collection.find().subscribe(new PrintToStringSubscriber<>()); |
| 180 | + |
| 181 | + .. output:: |
| 182 | + :language: none |
| 183 | + :visible: false |
| 184 | + |
| 185 | + Person{id='...', name='Ada Byron', age=20, address=Address{street='St James Square', city='London', zip='W1'}} |
| 186 | + Person{id='...', name='Charles Babbage', age=45, address=Address{street='5 Devonshire Street', city='London', zip='W11'}} |
| 187 | + Person{id='...', name='Alan Turing', age=28, address=Address{street='Bletchley Hall', city='Bletchley Park', zip='MK12'}} |
| 188 | + Person{id='...', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}} |
| 189 | + |
| 190 | +Specify a Query Filter |
| 191 | +---------------------- |
| 192 | + |
| 193 | +To query for ``Person`` instances that match certain conditions, pass a |
| 194 | +filter object to the ``find()`` method. To facilitate creating |
| 195 | +filter objects, the driver provides ``Filters`` helper methods. |
| 196 | + |
| 197 | +.. important:: |
| 198 | + |
| 199 | + When querying POJOs, you *must* query against the document field name |
| 200 | + and not the POJO property name. They are the same by default, but it |
| 201 | + is possible to change how POJO property names are mapped. |
| 202 | + |
| 203 | +Get a Single Person That Matches a Filter |
| 204 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 205 | + |
| 206 | +The following example finds the first ``Person`` in the database that |
| 207 | +has an ``address.city`` value of ``Wimborne`` by passing an ``eq()`` |
| 208 | +filter object to specify the equality condition: |
| 209 | + |
| 210 | +.. io-code-block:: |
| 211 | + :copyable: true |
| 212 | + |
| 213 | + .. input:: |
| 214 | + :language: java |
| 215 | + |
| 216 | + collection.find(eq("address.city", "Wimborne")) |
| 217 | + .first() |
| 218 | + .subscribe(new PrintToStringSubscriber<>()); |
| 219 | + |
| 220 | + .. output:: |
| 221 | + :language: none |
| 222 | + :visible: false |
| 223 | + |
| 224 | + Person{id='591dbc2550852fa685b3ad1a', name='Timothy Berners-Lee', age=61, address=Address{street='Colehill', city='Wimborne', zip='null'}} |
| 225 | + |
| 226 | +Get All Person Instances That Match a Filter |
| 227 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 228 | + |
| 229 | +The following example prints every document in which the value of |
| 230 | +``age`` is greater than ``30``: |
| 231 | + |
| 232 | +.. code-block:: java |
| 233 | + |
| 234 | + collection.find(gt("age", 30)).subscribe(new PrintToStringSubscriber<>()); |
| 235 | + |
| 236 | +Update Documents |
| 237 | +---------------- |
| 238 | + |
| 239 | +To update documents in a collection, you can use the collection's |
| 240 | +``updateOne()`` and ``updateMany()`` methods. |
| 241 | + |
| 242 | +Pass the following parameters to the methods: |
| 243 | + |
| 244 | +- Filter object to determine the document or documents to update. To |
| 245 | + specify an empty filter and match all ``Person`` instances, use an |
| 246 | + empty ``Document`` object. |
| 247 | +- Update document that specifies the modifications. To view a list of |
| 248 | + the available operators, see :manual:`Update Operators |
| 249 | + </reference/operator/update/>` in the Server manual. |
| 250 | + |
| 251 | +The update methods return an ``UpdateResult`` type that provides |
| 252 | +information about the operation, including the number of documents |
| 253 | +modified by the update. |
| 254 | + |
| 255 | +Update a Single Person |
| 256 | +~~~~~~~~~~~~~~~~~~~~~~ |
| 257 | + |
| 258 | +To update a single ``Person``, use the ``updateOne()`` method. |
| 259 | + |
| 260 | +The following example updates a ``Person`` named ``"Ada Byron"`` by |
| 261 | +setting their age to ``23`` and name to ``"Ada Lovelace"``: |
| 262 | + |
| 263 | +.. code-block:: java |
| 264 | + |
| 265 | + collection.updateOne( |
| 266 | + eq("name", "Ada Byron"), |
| 267 | + combine(set("age", 23), set("name", "Ada Lovelace")) |
| 268 | + ).subscribe(new OperationSubscriber<>()); |
| 269 | + |
| 270 | +Update Multiple Person Instances |
| 271 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 272 | + |
| 273 | +To update all ``Person`` instances that match a filter, use the |
| 274 | +``updateMany()`` method. |
| 275 | + |
| 276 | +The following example sets the ``zip`` field to ``null`` for all documents |
| 277 | +that have a ``zip`` value: |
| 278 | + |
| 279 | +.. code-block:: java |
| 280 | + |
| 281 | + collection.updateMany(not(eq("zip", null)), set("zip", null)) |
| 282 | + .subscribe(new OperationSubscriber<>()); |
| 283 | + |
| 284 | +Replace a Single Person |
| 285 | +~~~~~~~~~~~~~~~~~~~~~~~ |
| 286 | + |
| 287 | +Another way to change an existing ``Person`` instance is to use |
| 288 | +the ``replaceOne()`` method. |
| 289 | + |
| 290 | +The following example replaces a ``Person`` named ``"Ada Lovelace"`` |
| 291 | +with the ``Person`` instance referenced by the ``ada`` variable in the |
| 292 | +:ref:`preceding insertOne example <javars-pojo-insertone>`: |
| 293 | + |
| 294 | +.. code-block:: java |
| 295 | + |
| 296 | + collection.replaceOne(eq("name", "Ada Lovelace"), ada) |
| 297 | + .subscribe(new OperationSubscriber<>()); |
| 298 | + |
| 299 | +Delete Documents |
| 300 | +---------------- |
| 301 | + |
| 302 | +To delete documents from a collection, you can use the collection's ``deleteOne()`` and ``deleteMany()`` methods. |
| 303 | + |
| 304 | +Pass a filter object to match the document or |
| 305 | +documents to delete. To specify an empty filter, use an empty |
| 306 | +``Document`` object. |
| 307 | + |
| 308 | +The delete methods return a ``DeleteResult`` type that provides |
| 309 | +information about the operation, including the number of documents |
| 310 | +deleted. |
| 311 | + |
| 312 | +Delete a Single Person That Matches a Filter |
| 313 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 314 | + |
| 315 | +To delete a single ``Person`` that matches a filter, use the |
| 316 | +``deleteOne()`` method. |
| 317 | + |
| 318 | +The following example deletes one ``Person`` that has an |
| 319 | +``address.city`` value of ``Wimborne``: |
| 320 | + |
| 321 | +.. code-block:: java |
| 322 | + |
| 323 | + collection.deleteOne(eq("address.city", "Wimborne")) |
| 324 | + .subscribe(new OperationSubscriber<>()); |
| 325 | + |
| 326 | +Delete All Person Instances That Match a Filter |
| 327 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 328 | + |
| 329 | +To delete multiple ``Person`` instances that match a filter, use the |
| 330 | +``deleteMany()`` method. |
| 331 | + |
| 332 | +The following example deletes all ``Person`` instances that have an |
| 333 | +``address.city`` value of ``London``: |
| 334 | + |
| 335 | +.. code-block:: java |
| 336 | + |
| 337 | + collection.deleteMany(eq("address.city", "London")) |
| 338 | + .subscribe(new OperationSubscriber<>()); |
| 339 | + |
| 340 | +Additional Information |
| 341 | +~~~~~~~~~~~~~~~~~~~~~~ |
| 342 | + |
| 343 | +.. |
| 344 | + TODO update link |
| 345 | + To find additional tutorials, see the :ref:`Tutorials <>` section. |
0 commit comments