|
| 1 | +.. csharp-insert-guide: |
| 2 | + |
| 3 | +================ |
| 4 | +Insert Documents |
| 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 add documents to your MongoDB |
| 19 | +collections using insert operations. |
| 20 | + |
| 21 | +Sample Data |
| 22 | +~~~~~~~~~~~ |
| 23 | + |
| 24 | +The example in this guide uses the ``restaurants`` collection |
| 25 | +from the ``sample_restaurants`` database. The inserted documents in the |
| 26 | +example are modeled by the following ``Restaurant`` class: |
| 27 | + |
| 28 | +.. literalinclude:: /includes/fundamentals/code-examples/crud/insert.cs |
| 29 | + :language: csharp |
| 30 | + :dedent: |
| 31 | + :start-after: start-model |
| 32 | + :end-before: end-model |
| 33 | + |
| 34 | +This collection is from the :atlas:`sample datasets </sample-data>` provided |
| 35 | +by Atlas. See the :ref:`<csharp-quickstart>` to learn how to create a free MongoDB cluster |
| 36 | +and load this sample data. |
| 37 | + |
| 38 | +The ``_id`` Field |
| 39 | +----------------- |
| 40 | + |
| 41 | +In a MongoDB collection, each document *must* contain an ``_id`` field |
| 42 | +with a unique field value. |
| 43 | + |
| 44 | +MongoDB allows you to manage this field in two ways: |
| 45 | + |
| 46 | +- You can set this field for each document yourself, ensuring each |
| 47 | + ``_id`` field value is unique. |
| 48 | +- You can let the driver automatically generate unique ``ObjectId`` |
| 49 | + values for each document ``_id``. If you do not manually set an |
| 50 | + ``_id`` field value for a document, the driver will populate the field |
| 51 | + with an ``ObjectId``. |
| 52 | + |
| 53 | +Unless you provide strong guarantees for uniqueness, MongoDB recommends |
| 54 | +you let the driver automatically generate ``_id`` values. |
| 55 | + |
| 56 | +.. note:: |
| 57 | + |
| 58 | + Duplicate ``_id`` values violate unique index constraints, which |
| 59 | + causes the driver to return a ``MongoWriteException`` from |
| 60 | + ``InsertOne()`` or a ``MongoBulkWriteException`` from |
| 61 | + ``InsertMany()``. |
| 62 | + |
| 63 | +To learn more about the ``_id`` field, see the Server Manual Entry on |
| 64 | +:manual:`Unique Indexes </core/index-unique/>`. |
| 65 | + |
| 66 | +To learn more about document structure and rules, see the |
| 67 | +Server Manual Entry on :manual:`Documents </core/document>`. |
| 68 | + |
| 69 | +Insert Operations |
| 70 | +----------------- |
| 71 | + |
| 72 | +Use insert operations to add documents to a collection. You can perform |
| 73 | +inserts in MongoDB with the following methods: |
| 74 | + |
| 75 | +- ``InsertOne()``, which inserts a single document |
| 76 | +- ``InsertMany()``, which inserts multiple documents stored in an |
| 77 | + ``IEnumerable`` interface |
| 78 | + |
| 79 | +Insert One Document |
| 80 | +~~~~~~~~~~~~~~~~~~~ |
| 81 | + |
| 82 | +The following code shows how to use the asynchronous |
| 83 | +``InsertOneAsync()`` method or the synchronous ``InsertOne()`` method to |
| 84 | +insert one document. |
| 85 | + |
| 86 | +.. tabs:: |
| 87 | + |
| 88 | + .. tab:: Asynchronous |
| 89 | + :tabid: insert-one-async |
| 90 | + |
| 91 | + .. code-block:: csharp |
| 92 | + :copyable: true |
| 93 | + |
| 94 | + await _restaurantsCollection.InsertOneAsync(document); |
| 95 | + |
| 96 | + .. tab:: Synchronous |
| 97 | + :tabid: insert-one-sync |
| 98 | + |
| 99 | + .. code-block:: csharp |
| 100 | + :copyable: true |
| 101 | + |
| 102 | + _restaurantsCollection.InsertOne(document); |
| 103 | + |
| 104 | +Insert Multiple Documents |
| 105 | +~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 106 | + |
| 107 | +The following code shows how to use the asynchronous |
| 108 | +``InsertManyAsync()`` method or the synchronous ``InsertMany()`` method to |
| 109 | +insert multiple documents. |
| 110 | + |
| 111 | +.. tabs:: |
| 112 | + |
| 113 | + .. tab:: Asynchronous |
| 114 | + :tabid: insert-many-async |
| 115 | + |
| 116 | + .. code-block:: csharp |
| 117 | + :copyable: true |
| 118 | + |
| 119 | + await _restaurantsCollection.InsertManyAsync(docs); |
| 120 | + |
| 121 | + .. tab:: Synchronous |
| 122 | + :tabid: insert-many-sync |
| 123 | + |
| 124 | + .. code-block:: csharp |
| 125 | + :copyable: true |
| 126 | + |
| 127 | + _restaurantsCollection.InsertMany(docs); |
| 128 | + |
| 129 | +.. tip:: |
| 130 | + |
| 131 | + Find runnable examples using these methods under :ref:`additional |
| 132 | + information <additional-info>`. |
| 133 | + |
| 134 | +Parameters |
| 135 | +~~~~~~~~~~ |
| 136 | + |
| 137 | +The ``InsertOne()`` method takes the document you seek to insert as a |
| 138 | +parameter. The ``InsertMany()`` method takes an ``IEnumerable`` |
| 139 | +interface of documents, such as a list or array, as a parameter. |
| 140 | + |
| 141 | +The ``InsertOne()`` method optionally takes a ``InsertOneOptions`` type as an additional parameter, |
| 142 | +which represents options you can use to configure the insert operation. |
| 143 | +If you don't specify any ``InsertOneOptions`` properties, the driver does |
| 144 | +not customize the insert. |
| 145 | + |
| 146 | +The ``InsertOneOptions`` type allows you to configure options with the |
| 147 | +following properties: |
| 148 | + |
| 149 | +.. list-table:: |
| 150 | + :widths: 30 70 |
| 151 | + :header-rows: 1 |
| 152 | + |
| 153 | + * - Property |
| 154 | + - Description |
| 155 | + |
| 156 | + * - ``BypassDocumentValidation`` |
| 157 | + - | Gets or sets a value indicating whether to bypass document |
| 158 | + validation. If ``true``, allows the write to opt-out of |
| 159 | + :manual:`document level validation </core/schema-validation>`. |
| 160 | + |
| 161 | + * - ``Comment`` |
| 162 | + - | Gets or sets the comment for the operation. See :manual:`the delete command |
| 163 | + fields</reference/command/delete/#command-fields>` |
| 164 | + for more information. |
| 165 | + |
| 166 | +The ``InsertMany()`` method optionally takes a ``InsertManyOptions`` |
| 167 | +type as an additional parameter, which has the preceding |
| 168 | +``BypassDocumentValidation`` and ``Comment`` properties and the |
| 169 | +additional ``IsOrdered`` property: |
| 170 | + |
| 171 | +.. list-table:: |
| 172 | + :widths: 30 70 |
| 173 | + :header-rows: 1 |
| 174 | + |
| 175 | + * - Property |
| 176 | + - Description |
| 177 | + |
| 178 | + * - ``IsOrdered`` |
| 179 | + - | Gets or sets a value indicating whether the requests are |
| 180 | + fulfilled in order. If ``true``, the driver sends documents to the |
| 181 | + server in the order provided. If an error occurs, the driver |
| 182 | + and server abort all remaining insert operations. |
| 183 | + To learn more, see :ref:`Ordered Behavior<csharp-ordered-behavior>`. |
| 184 | + |
| 185 | + | Default: ``true`` |
| 186 | + |
| 187 | +Example |
| 188 | +~~~~~~~ |
| 189 | + |
| 190 | +The following code uses the ``InsertMany()`` method to insert four new |
| 191 | +``Restaurant`` documents into a collection with |
| 192 | +``BypassDocumentValidation`` set to ``true``: |
| 193 | + |
| 194 | +.. literalinclude:: /includes/fundamentals/code-examples/crud/insert.cs |
| 195 | + :language: csharp |
| 196 | + :dedent: |
| 197 | + :start-after: start-insert |
| 198 | + :end-before: end-insert |
| 199 | + |
| 200 | +The ``InsertMany()`` method has no return value. You can verify that |
| 201 | +your documents were successfully inserted by executing a ``Find()`` |
| 202 | +operation on the collection. For an example on how to find a document, |
| 203 | +see :ref:`csharp-find-one`. |
| 204 | + |
| 205 | +.. _csharp-ordered-behavior: |
| 206 | + |
| 207 | +Ordered Behavior |
| 208 | +~~~~~~~~~~~~~~~~ |
| 209 | + |
| 210 | +Assume you want to insert the following documents: |
| 211 | + |
| 212 | +.. code-block:: json |
| 213 | + :copyable: false |
| 214 | + |
| 215 | + { "_id" : 1, "name" : "Restaurant A" } |
| 216 | + { "_id" : 2, "name" : "Restaurant B" } |
| 217 | + { "_id" : 1, "name" : "Restaurant C" } |
| 218 | + { "_id" : 3, "name" : "Restaurant D" } |
| 219 | + |
| 220 | +If you attempt to insert these documents with default |
| 221 | +``InsertManyOptions``, the driver throws a ``MongoBulkWriteException`` at the third |
| 222 | +document because of the repeated ``_id`` value, but the documents before |
| 223 | +the error-producing document are still inserted into your collection. |
| 224 | + |
| 225 | +If you look inside your collection, you should be able to see the following documents: |
| 226 | + |
| 227 | +.. code-block:: json |
| 228 | + :copyable: false |
| 229 | + |
| 230 | + { "_id" : 1, "name" : "Restaurant A" } |
| 231 | + { "_id" : 2, "name" : "Restaurant B" } |
| 232 | + |
| 233 | +If you set ``IsOrdered`` to ``false`` in your insert operation, the driver will |
| 234 | +continue to insert your documents even if some documents produce errors. |
| 235 | +With this modified insert behavior, the driver throws an exception but inserts all documents |
| 236 | +that do not produce errors. |
| 237 | + |
| 238 | +If you look inside your collection, you should be able to see the following documents: |
| 239 | + |
| 240 | +.. code-block:: json |
| 241 | + :copyable: false |
| 242 | + |
| 243 | + { "_id" : 1, "name" : "Restaurant A" } |
| 244 | + { "_id" : 2, "name" : "Restaurant B" } |
| 245 | + { "_id" : 3, "name" : "Restaurant D" } |
| 246 | + |
| 247 | +.. _additional-info: |
| 248 | + |
| 249 | +Additional Information |
| 250 | +---------------------- |
| 251 | + |
| 252 | +For runnable examples of the insert operations, see the following usage |
| 253 | +examples: |
| 254 | + |
| 255 | +- :ref:`csharp-insert-one` |
| 256 | +- :ref:`csharp-insert-many` |
| 257 | + |
| 258 | +.. To learn more about performing the operations mentioned, see the |
| 259 | +.. following guides: |
| 260 | + |
| 261 | +.. - :ref:`csharp-query-document` |
| 262 | + |
| 263 | +.. - :doc:`Bulk Operations </fundamentals/crud/write-operations/bulk>` |
| 264 | + |
| 265 | +API Documentation |
| 266 | +~~~~~~~~~~~~~~~~~ |
| 267 | + |
| 268 | +To learn more about any of the methods or types discussed in this |
| 269 | +guide, see the following API Documentation: |
| 270 | + |
| 271 | +- `InsertOne() <{+api-root+}/Overload_MongoDB_Driver_IMongoCollection_1_InsertOne.htm>`__ |
| 272 | +- `InsertOneAsync() <{+api-root+}/Overload_MongoDB_Driver_IMongoCollection_1_InsertOneAsync.htm>`__ |
| 273 | +- `InsertMany() <{+api-root+}/Overload_MongoDB_Driver_IMongoCollection_1_InsertMany.htm>`__ |
| 274 | +- `InsertManyAsync() <{+api-root+}/Overload_MongoDB_Driver_IMongoCollection_1_InsertManyAsync.htm>`__ |
| 275 | +- `InsertOneOptions <{+api-root+}/T_MongoDB_Driver_InsertOneOptions.htm>`__ |
| 276 | +- `InsertManyOptions <{+api-root+}/T_MongoDB_Driver_InsertManyOptions.htm>`__ |
0 commit comments