-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathinsert.txt
310 lines (219 loc) · 8.79 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
.. _golang-insert-guide:
=================
Insert a Document
=================
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: code example, write operation, add data
:description: Learn how to insert documents into a MongoDB collection using the insertOne() and insertMany() methods, with options to modify their behavior.
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Overview
--------
In this guide, you can learn how to **insert** documents into a MongoDB
collection.
Before you can find, update, and delete documents in MongoDB, you must
insert those documents. You can insert one document by using the ``InsertOne()``
method, or insert multiple documents by using either the ``InsertMany()``
or ``BulkWrite()`` method.
The following sections focus on ``InsertOne()`` and ``InsertMany()``.
To learn how to use the ``BulkWrite()`` method, see the
:ref:`golang-bulk` guide.
.. _golang-insert-id:
The ``_id`` Field
-----------------
In MongoDB, each document *must* contain a unique ``_id`` field.
The two options for managing this field are:
- Managing this field yourself, ensuring that each value you use is unique.
- Letting the driver automatically generate unique ``ObjectId`` values. The
driver generates unique ``ObjectId`` values for documents that you do
not explicitly specify an ``_id``.
Unless you provide strong guarantees for 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 ``WriteError``.
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 a Document
-----------------
Use the ``InsertOne()`` method to insert a single document into a collection.
Upon successful insertion, the method returns an
``InsertOneResult`` instance that contains the ``_id`` of
the new document.
Example
~~~~~~~
This example uses the following ``Book`` struct as a model for documents
in the ``books`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/insertOptions.go
:start-after: start-book-struct
:end-before: end-book-struct
:language: go
:dedent:
The following example creates and inserts a document into the
``books`` collection using the ``InsertOne()`` method:
.. io-code-block::
:copyable: true
.. input::
:language: go
coll := client.Database("db").Collection("books")
doc := Book{Title: "Atonement", Author: "Ian McEwan"}
result, err := coll.InsertOne(context.TODO(), doc)
fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)
.. output::
:language: none
:visible: false
Inserted document with _id: ObjectID("...")
Modify ``InsertOne`` Behavior
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can modify the behavior of ``InsertOne()`` by constructing and passing
an optional ``InsertOneOptions`` struct. The available options to set with
``InsertOneOptions`` are:
.. list-table::
:header-rows: 1
:stub-columns: 1
:class: compatibility-large
* - Option
- Description
* - ``BypassDocumentValidation``
- | If ``true``, allows the write to opt-out of :manual:`document level validation </core/schema-validation>`.
| Default: ``false``
Construct an ``InsertOneOptions`` as follows:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/insertOptions.go
:start-after: // begin insertOneOpts
:end-before: // end insertOneOpts
:language: go
:copyable:
:dedent:
Insert Multiple Documents
-------------------------
Use the ``InsertMany()`` method to insert multiple documents into a
collection.
Upon successful insertion, the ``InsertMany()`` method returns an ``InsertManyResult``
instance that contains the ``_id`` fields of the inserted documents.
Example
~~~~~~~
The following example creates and inserts multiple documents into the
``books`` collection using the ``InsertMany()`` method:
.. code-block:: go
coll := client.Database("myDB").Collection("favorite_books")
docs := []interface{}{
Book{Title: "Cat's Cradle", Author: "Kurt Vonnegut Jr."},
Book{Title: "In Memory of Memory", Author: "Maria Stepanova"},
Book{Title: "Pride and Prejudice", Author: "Jane Austen"},
}
result, err := coll.InsertMany(context.TODO(), docs)
fmt.Printf("Documents inserted: %v\n", len(result.InsertedIDs))
for _, id := range result.InsertedIDs {
fmt.Printf("Inserted document with _id: %v\n", id)
}
After running the preceding code, your output resembles the following:
.. code-block:: none
:copyable: false
Documents inserted: 3
Inserted document with _id: ObjectID("...")
Inserted document with _id: ObjectID("...")
Inserted document with _id: ObjectID("...")
Modify ``InsertMany`` Behavior
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can modify the behavior of ``InsertMany()`` by constructing
and passing an optional ``InsertManyOptions`` struct. The available options
to set with ``InsertManyOptions`` are:
.. list-table::
:header-rows: 1
:stub-columns: 1
:class: compatibility-large
* - Option
- Description
* - ``BypassDocumentValidation``
- | If ``true``, allows the write to opt-out of :manual:`document level validation </core/schema-validation>`.
| Default: ``false``
* - ``Ordered``
- | If ``true``, the driver sends documents to the server in the order provided.
If an error occurs, the driver and server end all remaining insert operations.
To learn more, see :ref:`golang-ordered-behavior`.
| Default: ``false``
Construct an ``InsertManyOptions`` as follows:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/insertOptions.go
:start-after: // begin insertManyOpts
:end-before: // end insertManyOpts
:language: go
:copyable:
:dedent:
.. _golang-ordered-behavior:
``Ordered`` Behavior
~~~~~~~~~~~~~~~~~~~~
Assume you want to insert the following documents:
.. code-block:: json
:copyable: false
{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }
{ "_id": 1, "title": "Blueberries for Sal" }
{ "_id": 3, "title": "Goodnight Moon" }
If you attempt to insert these documents with default ``InsertManyOptions``, a
``BulkWriteException`` occurs at the third document because of the repeated
``_id`` value, but the documents before the error-producing document still get
inserted into your collection.
.. note::
You can get an acknowledgement of successful document insertion even
if a BulkWriteException occurs:
.. io-code-block::
:copyable: true
.. input::
:language: go
type Book struct {
ID int `bson:"_id"`
Title string
}
...
docs := []interface{}{
Book{ID: 1, Title: "Where the Wild Things Are"},
Book{ID: 2, Title: "The Very Hungry Caterpillar"},
Book{ID: 1, Title: "Blueberries for Sal"},
Book{ID: 3, Title: "Goodnight Moon"},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
fmt.Printf("A bulk write error occurred, but %v documents were still inserted.\n", len(result.InsertedIDs))
}
for _, id := range result.InsertedIDs {
fmt.Printf("Inserted document with _id: %v\n", id)
}
.. output::
:language: none
:visible: false
A bulk write error occurred, but 2 documents were still inserted.
Inserted document with _id: 1
Inserted document with _id: 2
After running the preceding code, your collection contains the following documents:
.. code-block:: json
:copyable: false
{ "_id": 1, "title": "Where the Wild Things Are" }
{ "_id": 2, "title": "The Very Hungry Caterpillar" }
Additional Information
----------------------
For runnable examples of the insert operations, see the following usage
examples:
- :ref:`golang-insert-one`
- :ref:`golang-insert-many`
To learn more about performing the operations mentioned, see the
following guides:
- :ref:`golang-query-document`
- :ref:`golang-bulk`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `WriteError <{+api+}/mongo#WriteError>`__
- `InsertOne() <{+api+}/mongo#Collection.InsertOne>`__
- `InsertOneResult <{+api+}/mongo#InsertOneResult>`__
- `InsertMany() <{+api+}/mongo#Collection.InsertMany>`__
- `InsertManyResult <{+api+}/mongo#InsertManyResult>`__
- `BulkWriteException <{+api+}/mongo#BulkWriteException>`__