|
| 1 | +.. _kotlin-sync-write-insert: |
| 2 | + |
| 3 | +================ |
| 4 | +Insert Documents |
| 5 | +================ |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 2 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +.. facet:: |
| 14 | + :name: genre |
| 15 | + :values: reference |
| 16 | + |
| 17 | +.. meta:: |
| 18 | + :keywords: code examples, write, save, create |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to use the {+driver-short+} to add |
| 24 | +documents to a MongoDB collection by performing **insert operations**. |
| 25 | + |
| 26 | +An insert operation inserts one or more documents into a MongoDB collection. |
| 27 | +You can perform an insert operation by using the ``insertOne()`` and |
| 28 | +``insertMany()`` methods. |
| 29 | + |
| 30 | +.. .. tip:: Interactive Lab |
| 31 | + |
| 32 | +.. This page includes a short interactive lab that demonstrates how to |
| 33 | +.. insert data by using the ``insertOne()`` method. You can complete this |
| 34 | +.. lab directly in your browser window without installing MongoDB or a code editor. |
| 35 | + |
| 36 | +.. To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the |
| 37 | +.. top of the page. To expand the lab to a full-screen format, click the |
| 38 | +.. full-screen button (:guilabel:`⛶`) in the top-right corner of the lab pane. |
| 39 | + |
| 40 | +Sample Data |
| 41 | +~~~~~~~~~~~ |
| 42 | + |
| 43 | +The examples in this guide use the ``sample_restaurants.restaurants`` collection |
| 44 | +from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a |
| 45 | +free MongoDB Atlas cluster and load the sample datasets, see the |
| 46 | +:atlas:`Get Started with Atlas </getting-started>` guide. |
| 47 | + |
| 48 | +The documents in this collection are modeled by the following {+language+} data class: |
| 49 | + |
| 50 | +.. literalinclude:: /includes/write/delete.kt |
| 51 | + :start-after: start-data-class |
| 52 | + :end-before: end-data-class |
| 53 | + :language: kotlin |
| 54 | + :copyable: |
| 55 | + :dedent: |
| 56 | + |
| 57 | +The ``_id`` Field |
| 58 | +----------------- |
| 59 | + |
| 60 | +In a MongoDB collection, each document *must* contain an ``_id`` field |
| 61 | +that has a unique value. |
| 62 | + |
| 63 | +MongoDB allows you to manage this field in two ways: |
| 64 | + |
| 65 | +- You can set this field for each document yourself, ensuring each |
| 66 | + ``_id`` field value is unique. |
| 67 | +- You can let the driver automatically generate a unique ``ObjectId`` |
| 68 | + value for each document ``_id``. If you do not manually set an |
| 69 | + ``_id`` value for a document, the driver populates the field |
| 70 | + with an ``ObjectId``. |
| 71 | + |
| 72 | +Unless you can guarantee uniqueness, we recommend |
| 73 | +letting the driver automatically generate ``_id`` values. |
| 74 | + |
| 75 | +.. note:: Duplicate _id Errors |
| 76 | + |
| 77 | + Setting duplicate ``_id`` values in a collection violates unique |
| 78 | + index constraints, which causes the driver to return a ``WriteError`` from |
| 79 | + the ``insertOne()`` method or a ``BulkWriteError`` from the |
| 80 | + ``insertMany()`` method. |
| 81 | + |
| 82 | +To learn more about the ``_id`` field, see the |
| 83 | +:manual:`Unique Indexes </core/index-unique/>` guide in the |
| 84 | +{+mdb-server+} manual. |
| 85 | + |
| 86 | +To learn more about document structure and rules, see the |
| 87 | +:manual:`Documents </core/document>` guide in the {+mdb-server+} manual. |
| 88 | + |
| 89 | +Insert One Document |
| 90 | +------------------- |
| 91 | + |
| 92 | +To add a single document to a MongoDB collection, call the ``insertOne()`` |
| 93 | +method and pass the document you want to add. |
| 94 | + |
| 95 | +The following example inserts a document into the ``restaurants`` |
| 96 | +collection: |
| 97 | + |
| 98 | +.. literalinclude:: /includes/write/insert.kt |
| 99 | + :start-after: start-insert-one |
| 100 | + :end-before: end-insert-one |
| 101 | + :language: kotlin |
| 102 | + :copyable: |
| 103 | + :dedent: |
| 104 | + |
| 105 | +Insert Multiple Documents |
| 106 | +------------------------- |
| 107 | + |
| 108 | +To add multiple documents to a MongoDB collection, user the ``insertMany()`` |
| 109 | +method and pass a list of documents you want to add. |
| 110 | + |
| 111 | +The following example inserts a list of documents into the |
| 112 | +``restaurants`` collection: |
| 113 | + |
| 114 | +.. literalinclude:: /includes/write/insert.kt |
| 115 | + :start-after: start-insert-many |
| 116 | + :end-before: end-insert-many |
| 117 | + :language: kotlin |
| 118 | + :copyable: |
| 119 | + :dedent: |
| 120 | + |
| 121 | +Modify Insert Behavior |
| 122 | +---------------------- |
| 123 | + |
| 124 | +The ``insertOne()`` method optionally accepts an ``InsertOneOptions`` |
| 125 | +parameter that sets options to configure the insert operation. |
| 126 | +If you don't specify any options, the driver performs the insert |
| 127 | +operation with default settings. Pass options as the last parameter to |
| 128 | +the ``insertOne()`` method. |
| 129 | + |
| 130 | +The following table describes the setter methods that you can use to |
| 131 | +configure an ``InsertOneOptions`` instance: |
| 132 | + |
| 133 | +.. list-table:: |
| 134 | + :widths: 30 70 |
| 135 | + :header-rows: 1 |
| 136 | + |
| 137 | + * - Method |
| 138 | + - Description |
| 139 | + |
| 140 | + * - ``bypassDocumentValidation()`` |
| 141 | + - | If set to ``true``, allows the driver to ignore |
| 142 | + :manual:`document-level validation </core/schema-validation>`. |
| 143 | + | Defaults to ``false``. |
| 144 | + |
| 145 | + * - ``comment()`` |
| 146 | + - | Sets a comment to attach to the operation. For more information, see the :manual:`insert command |
| 147 | + fields </reference/command/insert/#command-fields>` guide in the |
| 148 | + {+mdb-server+} manual for more information. |
| 149 | + |
| 150 | +You can set the preceding settings on the ``insertMany()`` method |
| 151 | +by configuring an ``InsertManyOptions`` instance. You can also use the |
| 152 | +``ordered()`` method setter method to specify the order in which the driver |
| 153 | +inserts documents into MongoDB: |
| 154 | + |
| 155 | +.. list-table:: |
| 156 | + :widths: 30 70 |
| 157 | + :header-rows: 1 |
| 158 | + |
| 159 | + * - Method |
| 160 | + - Description |
| 161 | + |
| 162 | + * - ``ordered()`` |
| 163 | + - | If set to ``true``, the driver sends documents to the |
| 164 | + server in the order provided. If an error occurs, the driver |
| 165 | + cancels all remaining insert operations. |
| 166 | + | Defaults to ``true``. |
| 167 | + |
| 168 | +Pass options as the last parameter to the ``insertMany()`` method. |
| 169 | + |
| 170 | +Modify Insert Example |
| 171 | +~~~~~~~~~~~~~~~~~~~~~ |
| 172 | + |
| 173 | +The following code uses the ``bypassDocumentValidation()`` method to |
| 174 | +set the option to ignore document validation rules. Then, the example uses the |
| 175 | +``insertMany()`` method to add new documents to the ``restaurants`` |
| 176 | +collection. |
| 177 | + |
| 178 | +.. literalinclude:: /includes/write/insert.kt |
| 179 | + :start-after: start-insert-opts |
| 180 | + :end-before: end-insert-opts |
| 181 | + :language: kotlin |
| 182 | + :copyable: |
| 183 | + :dedent: |
| 184 | + |
| 185 | +Return Value |
| 186 | +------------ |
| 187 | + |
| 188 | +The ``insertOne()`` method returns an ``InsertOneResult`` instance, and |
| 189 | +the ``insertMany()`` method returns an ``InsertManyResult`` instance. |
| 190 | + |
| 191 | +You can use the following methods to retrieve information from |
| 192 | +an ``InsertOneResult`` instance: |
| 193 | + |
| 194 | +.. list-table:: |
| 195 | + :widths: 30 70 |
| 196 | + :header-rows: 1 |
| 197 | + |
| 198 | + * - Method |
| 199 | + - Description |
| 200 | + |
| 201 | + * - ``getInsertedId()`` |
| 202 | + - Indicates the ``_id`` value of the inserted document. |
| 203 | + |
| 204 | + * - ``wasAcknowledged()`` |
| 205 | + - Returns ``true`` if the server acknowledges the result. |
| 206 | + |
| 207 | +You can use the following methods to retrieve information from |
| 208 | +an ``InsertOneResult`` instance: |
| 209 | + |
| 210 | +.. list-table:: |
| 211 | + :widths: 30 70 |
| 212 | + :header-rows: 1 |
| 213 | + |
| 214 | + * - Method |
| 215 | + - Description |
| 216 | + |
| 217 | + * - ``getInsertedIds()`` |
| 218 | + - Indicates the ``_id`` values of the inserted documents. |
| 219 | + |
| 220 | + * - ``wasAcknowledged()`` |
| 221 | + - Returns ``true`` if the server acknowledges the result. |
| 222 | + |
| 223 | +.. note:: |
| 224 | + |
| 225 | + If the ``wasAcknowledged()`` method returns ``false``, trying to |
| 226 | + access the ``_id`` values results in an |
| 227 | + ``InvalidOperation`` exception. The driver cannot |
| 228 | + determine these values if the server does not acknowledge the write |
| 229 | + operation. |
| 230 | + |
| 231 | +Additional Information |
| 232 | +---------------------- |
| 233 | + |
| 234 | +For runnable code examples that demonstrate how to insert documents by |
| 235 | +using the {+driver-short+}, see :ref:`kotlin-sync-write`. |
| 236 | + |
| 237 | +API Documentation |
| 238 | +~~~~~~~~~~~~~~~~~ |
| 239 | + |
| 240 | +To learn more about any of the methods or types discussed in this |
| 241 | +guide, see the following API documentation: |
| 242 | + |
| 243 | +- `insertOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/insert-one.html>`__ |
| 244 | +- `insertMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/insert-many.html>`__ |
| 245 | +- `InsertOneOptions <{+core-api+}/com/mongodb/client/model/InsertOneOptions.html>`__ |
| 246 | +- `InsertManyOptions <{+core-api+}/com/mongodb/client/model/InsertManyOptions.html>`__ |
| 247 | +- `InsertOneResult <{+core-api+}/com/mongodb/client/result/InsertOneResult.html>`__ |
| 248 | +- `InsertManyResult <{+core-api+}/com/mongodb/client/result/InsertManyResult.html>`__ |
| 249 | + |
| 250 | +.. .. instruqt:: |
| 251 | +.. :title: insertOne() Lesson |
| 252 | +.. :drawer: |
0 commit comments