|
| 1 | +.. _scala-case-class-qs: |
| 2 | + |
| 3 | +================================= |
| 4 | +Quick Start (Case Class Examples) |
| 5 | +================================= |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: tutorial |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: code example, get started, connect, change data, case class |
| 13 | + |
| 14 | +.. contents:: On this page |
| 15 | + :local: |
| 16 | + :backlinks: none |
| 17 | + :depth: 2 |
| 18 | + :class: singlecol |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +This guide is similar to the :ref:`Quick Start guide |
| 24 | +<scala-quickstart>` but uses case classes to |
| 25 | +model documents instead of the generic ``Document`` class. |
| 26 | + |
| 27 | +The code examples in this guide come from the `QuickTourCaseClass.scala |
| 28 | +<{+driver-source-gh+}/blob/master/driver-scala/src/integration/scala/tour/QuickTourCaseClass.scala>`__ |
| 29 | +file in the driver source code GitHub repository. |
| 30 | + |
| 31 | +.. important:: |
| 32 | + |
| 33 | + See the :ref:`BSON Macros <scala-macros>` documentation for information about |
| 34 | + using macros for configuring case class support with your |
| 35 | + ``MongoCollection`` instance. |
| 36 | + |
| 37 | +First, create the case class you want to use to represent the |
| 38 | +documents in the collection. The following code creates a ``Person`` case |
| 39 | +class and companion object: |
| 40 | + |
| 41 | +.. code-block:: scala |
| 42 | + |
| 43 | + import org.mongodb.scala.bson.ObjectId |
| 44 | + |
| 45 | + object Person { |
| 46 | + def apply(firstName: String, lastName: String): Person = |
| 47 | + Person(new ObjectId(), firstName, lastName) |
| 48 | + } |
| 49 | + case class Person(_id: ObjectId, firstName: String, lastName: String) |
| 50 | + |
| 51 | +.. note:: |
| 52 | + |
| 53 | + In the companion object, the ``apply()`` method can automatically |
| 54 | + assign an ``_id`` value when creating new instances that don’t include one. In |
| 55 | + MongoDB the ``_id`` field represents the primary key for a document, so by |
| 56 | + having an ``_id`` field in the case class, you allow access to the primary |
| 57 | + key. |
| 58 | + |
| 59 | +Configuring Case Classes |
| 60 | +------------------------ |
| 61 | + |
| 62 | +When using ``Person`` with a collection, there must be a ``Codec`` that can |
| 63 | +convert it to and from BSON. The ``org.mongodb.scala.bson.codecs.Macros`` |
| 64 | +companion object provides macros that can automatically generate a codec |
| 65 | +for case classes at compile time. The following example creates a |
| 66 | +new ``CodecRegistry`` that includes a codec for the ``Person`` case |
| 67 | +class: |
| 68 | + |
| 69 | +.. code-block:: scala |
| 70 | + |
| 71 | + import org.mongodb.scala.bson.codecs.Macros._ |
| 72 | + import org.mongodb.scala.MongoClient.DEFAULT_CODEC_REGISTRY |
| 73 | + import org.bson.codecs.configuration.CodecRegistries.{fromRegistries, fromProviders} |
| 74 | + |
| 75 | + val codecRegistry = fromRegistries(fromProviders(classOf[Person]), DEFAULT_CODEC_REGISTRY ) |
| 76 | + |
| 77 | +Once the ``CodecRegistry`` is configured, the next step is to create a |
| 78 | +``MongoCollection[Person]``. The following example uses the ``test`` collection from |
| 79 | +the ``mydb`` database: |
| 80 | + |
| 81 | +.. code-block:: scala |
| 82 | + |
| 83 | + val mongoClient: MongoClient = MongoClient() |
| 84 | + val database: MongoDatabase = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry) |
| 85 | + val collection: MongoCollection[Person] = database.getCollection("test") |
| 86 | + |
| 87 | +.. note:: |
| 88 | + |
| 89 | + The ``CodecRegistry`` can be set when creating a ``MongoClient``, at the |
| 90 | + database level, or at the collection level. The API is flexible, allowing |
| 91 | + for different ``CodecRegistry`` instances as required. |
| 92 | + |
| 93 | +Insert a Person |
| 94 | +--------------- |
| 95 | + |
| 96 | +With the correctly configured ``MongoCollection``, inserting ``Person`` |
| 97 | +instances into the collection is simple: |
| 98 | + |
| 99 | +.. code-block:: scala |
| 100 | + |
| 101 | + val person: Person = Person("Ada", "Lovelace") |
| 102 | + collection.insertOne(person).results() |
| 103 | + |
| 104 | +Insert Multiple Person Instances |
| 105 | +-------------------------------- |
| 106 | + |
| 107 | +To insert multiple ``Person`` instances, use the ``insertMany()`` |
| 108 | +method. The following example uses the ``printResults()`` implicit and |
| 109 | +blocks until the observer is completed and then prints each result: |
| 110 | + |
| 111 | +.. code-block:: scala |
| 112 | + |
| 113 | + val people: Seq[Person] = Seq( |
| 114 | + Person("Charles", "Babbage"), |
| 115 | + Person("George", "Boole"), |
| 116 | + Person("Gertrude", "Blanch"), |
| 117 | + Person("Grace", "Hopper"), |
| 118 | + Person("Ida", "Rhodes"), |
| 119 | + Person("Jean", "Bartik"), |
| 120 | + Person("John", "Backus"), |
| 121 | + Person("Lucy", "Sanders"), |
| 122 | + Person("Tim", "Berners Lee"), |
| 123 | + Person("Zaphod", "Beeblebrox") |
| 124 | + ) |
| 125 | + |
| 126 | + collection.insertMany(people).printResults() |
| 127 | + |
| 128 | +This code outputs the following message: |
| 129 | + |
| 130 | +.. code-block:: none |
| 131 | + |
| 132 | + The operation completed successfully |
| 133 | + |
| 134 | +Querying the Collection |
| 135 | +----------------------- |
| 136 | + |
| 137 | +Use the ``find()`` method to query a collection. |
| 138 | + |
| 139 | +Find the First Matching Person |
| 140 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 141 | + |
| 142 | +Querying the collection uses the same API used in the Quick Start: |
| 143 | + |
| 144 | +.. code-block:: scala |
| 145 | + |
| 146 | + collection.find().first().printHeadResult() |
| 147 | + |
| 148 | +The example prints the first ``Person`` in the collection: |
| 149 | + |
| 150 | +.. code-block:: none |
| 151 | + |
| 152 | + Person(58dd0a68218de22333435fa4, Ada, Lovelace) |
| 153 | + |
| 154 | +Return All Documents |
| 155 | +~~~~~~~~~~~~~~~~~~~~ |
| 156 | + |
| 157 | +To retrieve all the documents in the collection, use the ``find()`` method. The |
| 158 | +``find()`` method returns a ``FindObservable`` instance that provides a fluent |
| 159 | +interface for chaining or controlling find operations. The following |
| 160 | +uses prints all the documents in the collection as ``Person`` instances: |
| 161 | + |
| 162 | +.. code-block:: scala |
| 163 | + |
| 164 | + collection.find().printResults() |
| 165 | + |
| 166 | +Retrieve a Person By Using a Query Filter |
| 167 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 168 | + |
| 169 | +To return a subset of the documents in our collection, pass a filter to |
| 170 | +the ``find()`` method. For example, the following example returns the first |
| 171 | +``Person`` whose first name is ``"Ida"``: |
| 172 | + |
| 173 | +.. code-block:: scala |
| 174 | + |
| 175 | + import org.mongodb.scala.model.Filters._ |
| 176 | + |
| 177 | + collection.find(equal("firstName", "Ida")).first().printHeadResult() |
| 178 | + |
| 179 | +This example outputs the following result: |
| 180 | + |
| 181 | +.. code-block:: none |
| 182 | + |
| 183 | + Person(58dd0a68218de22333435fa4, Ida, Rhodes) |
| 184 | + |
| 185 | +.. tip:: |
| 186 | + |
| 187 | + You can use the ``Filters``, ``Sorts``, ``Projections`` and |
| 188 | + ``Updates`` helpers to enable simple and concise ways of building queries. |
| 189 | + |
| 190 | +Find Matching Person Instances |
| 191 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 192 | + |
| 193 | +The following filter finds all ``Person`` instances where the |
| 194 | +``firstName`` starts with ``"G"``, sorted by ``lastName``: |
| 195 | + |
| 196 | +.. code-block:: scala |
| 197 | + |
| 198 | + collection.find(regex("firstName", "^G")).sort(ascending("lastName")).printResults() |
| 199 | + |
| 200 | +This example prints out the ``Person`` instances for ``"Gertrude"``, ``"George"`` and ``"Grace"``. |
| 201 | + |
| 202 | +Update Documents |
| 203 | +---------------- |
| 204 | + |
| 205 | +There are many :manual:`update operators |
| 206 | +</reference/operator/update/>` supported by MongoDB. Use the ``Updates`` |
| 207 | +helpers to help update documents in a collection. |
| 208 | + |
| 209 | +The following update corrects the hyphenation for ``"Tim Berners-Lee"``: |
| 210 | + |
| 211 | +.. code-block:: scala |
| 212 | + |
| 213 | + collection.updateOne(equal("lastName", "Berners Lee"), set("lastName", "Berners-Lee")) |
| 214 | + .printHeadResult("Update Result: ") |
| 215 | + |
| 216 | +The update methods return an ``UpdateResult``, which provides |
| 217 | +information about the operation, including the number of documents |
| 218 | +modified by the update. |
| 219 | + |
| 220 | +Delete Documents |
| 221 | +---------------- |
| 222 | + |
| 223 | +To delete at most a single document, or none if no documents match the |
| 224 | +filter, use the ``deleteOne()`` method: |
| 225 | + |
| 226 | +.. code-block:: scala |
| 227 | + |
| 228 | + collection.deleteOne(equal("firstName", "Zaphod")).printHeadResult("Delete Result: ") |
0 commit comments