Skip to content

Commit b122b68

Browse files
authored
DOCSP-41127: insert docs (mongodb#20)
* DOCSP-41127: insert docs * AS PR fixes 1 * add write to toc landing array
1 parent 6bb165f commit b122b68

File tree

6 files changed

+308
-10
lines changed

6 files changed

+308
-10
lines changed

snooty.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ intersphinx = [ "https://www.mongodb.com/docs/manual/objects.inv",
77
]
88

99
toc_landing_pages = [
10+
"/write-operations",
1011
"/get-started",
1112
"/read",
1213
"/connect",

source/includes/write/delete.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ fun main() {
1111

1212
val mongoClient = MongoClient.create(uri)
1313
val database = mongoClient.getDatabase("sample_restaurants")
14-
val collection = database.getCollection<Movie>("restaurants")
14+
val collection = database.getCollection<Restaurant>("restaurants")
1515

1616
// start-delete-one
1717
val filter = eq(Restaurant::name.name, "Happy Garden")

source/includes/write/insert.kt

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import com.mongodb.client.model.DeleteOptions
2+
import com.mongodb.client.model.Filters.*
3+
import com.mongodb.client.model.InsertManyOptions
4+
import com.mongodb.kotlin.client.MongoClient
5+
6+
// start-data-class
7+
data class Restaurant(val name: String, val borough: String)
8+
// end-data-class
9+
10+
fun main() {
11+
val uri = "<connection string>"
12+
13+
val mongoClient = MongoClient.create(uri)
14+
val database = mongoClient.getDatabase("sample_restaurants")
15+
val collection = database.getCollection<Restaurant>("restaurants")
16+
17+
// start-insert-one
18+
val doc = Restaurant("Sea Shell Bar", "Queens")
19+
val result = collection.insertOne(doc)
20+
// end-insert-one
21+
22+
// start-insert-many
23+
val docs = listOf(
24+
Restaurant("Full Moon Grill", "Queens"),
25+
Restaurant("King's Cup", "Manhattan"),
26+
)
27+
28+
val result = collection.insertMany(docs)
29+
// end-insert-many
30+
31+
// start-insert-opts
32+
val opts = InsertManyOptions().bypassDocumentValidation(true)
33+
val docs = listOf(
34+
Restaurant("Full Moon Grill", "Queens"),
35+
Restaurant("King's Cup", "Manhattan"),
36+
)
37+
38+
val result = collection.insertMany(docs, opts)
39+
// end-insert-opts
40+
41+
}
42+

source/write-operations.txt

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ Write Data to MongoDB
2222
:titlesonly:
2323
:maxdepth: 1
2424

25+
/write/insert
2526
/write/update
2627
/write/delete
2728

2829
..
29-
/write/insert
3030
/write/replace
3131
/write/bulk-write
3232
/write/gridfs
@@ -40,8 +40,8 @@ methods that you can use to write data to MongoDB by using the
4040

4141
.. tip::
4242

43-
To learn more about any of the methods shown on this page, see the link
44-
provided in each section.
43+
To learn more about any of the methods shown on this page, see the link
44+
provided in each section.
4545

4646
To use an example from this page, copy the code example into the
4747
:ref:`sample application <kotlin-sync-write-sample>` or your own application.
@@ -71,8 +71,8 @@ collection:
7171
:copyable:
7272
:dedent:
7373

74-
.. To learn more about the ``insert_one()`` method, see the :ref:`Insert Documents
75-
.. <kotlin-sync-write-insert>` guide.
74+
To learn more about the ``insertOne()`` method, see the :ref:`Insert Documents
75+
<kotlin-sync-write-insert>` guide.
7676

7777
Insert Multiple
7878
---------------
@@ -87,8 +87,8 @@ collection:
8787
:copyable:
8888
:dedent:
8989

90-
.. To learn more about the ``insert_many()`` method, see the :ref:`Insert Documents
91-
.. <kotlin-sync-write-insert>` guide.
90+
To learn more about the ``insertMany()`` method, see the :ref:`Insert Documents
91+
<kotlin-sync-write-insert>` guide.
9292

9393
Update One
9494
----------

source/write/delete.txt

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ configure a ``DeleteOptions`` instance:
108108
:widths: 30 70
109109
:header-rows: 1
110110

111-
* - Property
111+
* - Method
112112
- Description
113113

114114
* - ``collation()``
@@ -140,6 +140,9 @@ configure a ``DeleteOptions`` instance:
140140
fields </reference/command/delete/#command-fields>` guide in the
141141
{+mdb-server+} manual for more information.
142142

143+
Modify Delete Example
144+
`````````````````````
145+
143146
The following code creates options and uses the ``comment()`` method to
144147
add a comment to the delete operation. Then, the example uses the
145148
``deleteMany()`` method to delete all documents in the ``restaurants``
@@ -185,7 +188,7 @@ API Documentation
185188
~~~~~~~~~~~~~~~~~
186189

187190
To learn more about any of the methods or types discussed in this
188-
guide, see the following API Documentation:
191+
guide, see the following API documentation:
189192

190193
- `deleteOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/delete-one.html>`__
191194
- `deleteMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/delete-many.html>`__

source/write/insert.txt

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
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

Comments
 (0)