-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathinsert.txt
310 lines (219 loc) · 9.66 KB
/
insert.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
.. _csharp-insert-guide:
================
Insert Documents
================
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: bulk, synchronous, asynchronous
:description: Learn to use the MongoDB .NET/C# Driver for inserting documents into a collection, with options for synchronous and asynchronous operations.
Overview
--------
In this guide, you can learn how to use the {+driver-long+} to add
documents to a MongoDB collection by performing insert operations.
.. note:: 16 MB Size Limit
MongoDB limits individual BSON documents to 16 MB. If your document is larger than 16 MB,
use the :ref:`GridFS <csharp-gridfs>` API instead.
An insert operation inserts one or more documents into a MongoDB collection.
The {+driver-short+} provides the following methods to perform insert
operations, each of which has a synchronous and asynchronous version:
- ``InsertOne() or ``InsertOneAsync()``
- ``InsertMany()`` or ``InsertManyAsync()``
.. tip:: Interactive Lab
This page includes a short interactive lab that demonstrates how to
insert data by using the ``InsertOneAsync()`` method. You can complete this
lab directly in your browser window without installing MongoDB or a code editor.
To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the
top of the page. To expand the lab to a full-screen format, click the
full-screen button (:guilabel:`⛶`) in the top-right corner of the lab pane.
Sample Data
~~~~~~~~~~~
The examples in this guide use the ``restaurants`` collection
from the ``sample_restaurants`` database. The documents in this
collection use the following ``Restaurant``, ``Address``, and ``GradeEntry``
classes as models:
.. literalinclude:: /includes/code-examples/Restaurant.cs
:language: csharp
:copyable:
:dedent:
.. literalinclude:: /includes/code-examples/Address.cs
:language: csharp
:copyable:
:dedent:
.. literalinclude:: /includes/code-examples/GradeEntry.cs
:language: csharp
:copyable:
:dedent:
.. include:: /includes/convention-pack-note.rst
This collection is from the :atlas:`sample datasets </sample-data>` provided
by Atlas. See the :ref:`<csharp-quickstart>` to learn how to create a free MongoDB cluster
and load this sample data.
The ``_id`` Field
-----------------
In a MongoDB collection, each document *must* contain an ``_id`` field
with a unique field value.
MongoDB allows you to manage this field in two ways:
- You can set this field for each document yourself, ensuring each
``_id`` field value is unique.
- You can let the driver automatically generate unique ``ObjectId``
values for each document ``_id``. If you do not manually set an
``_id`` field value for a document, the driver will populate the field
with an ``ObjectId``.
Unless you can guarantee uniqueness, MongoDB recommends
you let the driver automatically generate ``_id`` values.
.. note::
Duplicate ``_id`` values violate unique index constraints, which
causes the driver to return a ``MongoWriteException`` from
``InsertOne()`` or a ``MongoBulkWriteException`` from
``InsertMany()``.
To learn more about the ``_id`` field, see the Server Manual Entry on
:manual:`Unique Indexes </core/index-unique/>`.
To learn more about document structure and rules, see the
Server Manual Entry on :manual:`Documents </core/document>`.
Insert One Document
-------------------
The following code shows how to use the synchronous ``InsertOne()`` method or the asynchronous
``InsertOneAsync()`` method to insert one document.
.. tabs::
.. tab:: Synchronous
:tabid: insert-one-sync
.. code-block:: csharp
:copyable: true
_restaurantsCollection.InsertOne(document);
.. tab:: Asynchronous
:tabid: insert-one-async
.. code-block:: csharp
:copyable: true
await _restaurantsCollection.InsertOneAsync(document);
Insert Multiple Documents
-------------------------
The following code shows how to use the synchronous ``InsertMany()`` method or the asynchronous
``InsertManyAsync()`` method to insert multiple documents.
.. tabs::
.. tab:: Synchronous
:tabid: insert-many-sync
.. code-block:: csharp
:copyable: true
_restaurantsCollection.InsertMany(docs);
.. tab:: Asynchronous
:tabid: insert-many-async
.. code-block:: csharp
:copyable: true
await _restaurantsCollection.InsertManyAsync(docs);
.. tip::
Find runnable examples using these methods under :ref:`additional
information <additional-info>`.
Modify Insert Behavior
----------------------
The ``InsertOne()`` method takes the document you seek to insert as a
parameter. The ``InsertMany()`` method takes an ``IEnumerable``
collection of documents, such as a list or array, as a parameter.
The ``InsertOne()`` method optionally takes a ``InsertOneOptions`` type as an additional parameter,
which represents options you can use to configure the insert operation.
If you don't specify any ``InsertOneOptions`` properties, the driver does
not customize the insert.
The ``InsertOneOptions`` type allows you to configure options with the
following properties:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Property
- Description
* - ``BypassDocumentValidation``
- | Gets or sets a value indicating whether to bypass document
validation. If ``true``, allows the write to opt-out of
:manual:`document level validation </core/schema-validation>`.
* - ``Comment``
- | Gets or sets the comment for the operation. See :manual:`the insert command
fields</reference/command/insert/#command-fields>`
for more information.
The ``InsertMany()`` method optionally takes a ``InsertManyOptions``
type as an additional parameter, which has the preceding
``BypassDocumentValidation`` and ``Comment`` properties and the
additional ``IsOrdered`` property:
.. list-table::
:widths: 30 70
:header-rows: 1
* - Property
- Description
* - ``IsOrdered``
- | Gets or sets a value indicating whether the requests are
fulfilled in order. If ``true``, the driver sends documents to the
server in the order provided. If an error occurs, the driver
and server abort all remaining insert operations.
To learn more, see :ref:`Ordered Behavior<csharp-ordered-behavior>`.
| Default: ``true``
Example
~~~~~~~
The following code uses the ``InsertMany()`` method to insert five new
``Restaurant`` documents into a collection with
``BypassDocumentValidation`` set to ``true``:
.. literalinclude:: /includes/code-examples/insert-many/InsertMany.cs
:language: csharp
:dedent:
:start-after: start-insert-many-with-options
:end-before: end-insert-many-with-options
The ``InsertMany()`` method has no return value. You can verify that
your documents were successfully inserted by executing a ``Find()``
operation on the collection. For an example on how to find a document,
see :ref:`csharp-find-one`.
.. _csharp-ordered-behavior:
Specify Ordered Behavior
------------------------
Assume you want to insert the following documents:
.. code-block:: json
:copyable: false
{ "_id" : 1, "name" : "Restaurant A" }
{ "_id" : 2, "name" : "Restaurant B" }
{ "_id" : 1, "name" : "Restaurant C" }
{ "_id" : 3, "name" : "Restaurant D" }
If you attempt to insert these documents with default
``InsertManyOptions``, the driver throws a ``MongoBulkWriteException`` at the third
document because of the repeated ``_id`` value, but the documents before
the error-producing document are still inserted into your collection.
If you look inside your collection, you should be able to see the following documents:
.. code-block:: json
:copyable: false
{ "_id" : 1, "name" : "Restaurant A" }
{ "_id" : 2, "name" : "Restaurant B" }
If you set ``IsOrdered`` to ``false`` in your insert operation, the driver will
continue to insert your documents even if some documents produce errors.
With this modified insert behavior, the driver throws an exception but inserts all documents
that do not produce errors.
If you look inside your collection, you should be able to see the following documents:
.. code-block:: json
:copyable: false
{ "_id" : 1, "name" : "Restaurant A" }
{ "_id" : 2, "name" : "Restaurant B" }
{ "_id" : 3, "name" : "Restaurant D" }
.. _additional-info:
Additional Information
----------------------
For runnable examples of the insert operations, see the following usage
examples:
- :ref:`csharp-insert-one`
- :ref:`csharp-insert-many`
.. To learn more about performing the operations mentioned, see the
.. following guides:
.. - :ref:`csharp-query-document`
.. - :doc:`Bulk Operations </fundamentals/crud/write-operations/bulk>`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `InsertOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertOne.html>`__
- `InsertOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertOneAsync.html>`__
- `InsertMany() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertMany.html>`__
- `InsertManyAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.InsertManyAsync.html>`__
- `InsertOneOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.InsertOneOptions.html>`__
- `InsertManyOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.InsertManyOptions.html>`__
.. _csharp-insert-instruqt-lab:
.. instruqt:: /mongodb-docs/tracks/insert-a-document---c-net-driver?token=em__BF-Ccd2b1dS3YLi
:title: InsertOneAsync() Lesson
:drawer: