Skip to content

Commit 843f43a

Browse files
committed
DOCSP-41127: insert docs
1 parent 0379473 commit 843f43a

File tree

5 files changed

+276
-10
lines changed

5 files changed

+276
-10
lines changed

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,10 +22,10 @@ Write Data to MongoDB
2222
:titlesonly:
2323
:maxdepth: 1
2424

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

2728
..
28-
/write/insert
2929
/write/update
3030
/write/replace
3131
/write/bulk-write
@@ -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: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
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 a parameter
125+
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.
128+
129+
The following table describes the setter methods that you can use to
130+
configure an ``InsertOneOptions`` instance:
131+
132+
.. list-table::
133+
:widths: 30 70
134+
:header-rows: 1
135+
136+
* - Property
137+
- Description
138+
139+
* - ``bypassDocumentValidation()``
140+
- | If set to ``true``, allows the driver to ignore
141+
:manual:`document-level validation </core/schema-validation>`.
142+
| Defaults to ``false``.
143+
144+
* - ``comment()``
145+
- | Sets a comment to attach to the operation. For more information, see the :manual:`insert command
146+
fields </reference/command/insert/#command-fields>` guide in the
147+
{+mdb-server+} manual for more information.
148+
149+
You can set the preceding settings on the ``insertMany()`` method
150+
by configuring an ``InsertManyOptions`` instance. You can also use the
151+
``ordered()`` method setter method to specify the order in which the driver
152+
inserts documents into MongoDB. If set to ``true``, the driver sends documents to the
153+
server in the order provided. If an error occurs, the driver and server
154+
cancel all remaining insert operations. The driver performs ordered
155+
inserts by default.
156+
157+
Modify Insert Example
158+
~~~~~~~~~~~~~~~~~~~~~
159+
160+
The following code creates options and uses the ``bypassDocumentValidation()`` method to
161+
ignore document validation rules. Then, the example uses the
162+
``insertMany()`` method to add new documents to the ``restaurants``
163+
collection.
164+
165+
.. literalinclude:: /includes/write/insert.kt
166+
:start-after: start-insert-opts
167+
:end-before: end-insert-opts
168+
:language: kotlin
169+
:copyable:
170+
:dedent:
171+
172+
Return Value
173+
------------
174+
175+
The ``insertOne()`` method returns an ``InsertOneResult`` instance, and
176+
the ``insertMany()`` method returns an ``InsertManyResult`` instance.
177+
178+
You can use the following methods to retrieve information from
179+
an ``InsertOneResult`` instance:
180+
181+
- ``getInsertedId()``, which indicates the ``_id`` value of the inserted document
182+
- ``wasAcknowledged()``, which returns ``true`` if the server
183+
acknowledges the result
184+
185+
You can use the following methods to retrieve information from
186+
an ``InsertOneResult`` instance:
187+
188+
- ``getInsertedIds()``, which indicates the ``_id`` values of the inserted documents
189+
- ``wasAcknowledged()``, which returns ``true`` if the server
190+
acknowledges the result
191+
192+
.. note::
193+
194+
If the ``wasAcknowledged()`` method returns ``false``, trying to
195+
access the ``_id`` values results in an
196+
``InvalidOperation`` exception. The driver cannot
197+
determine these values if the server does not acknowledge the write
198+
operation.
199+
200+
Additional Information
201+
----------------------
202+
203+
For runnable code examples that demonstrate how to insert documents by
204+
using the {+driver-short+}, see :ref:`kotlin-sync-write`.
205+
206+
API Documentation
207+
~~~~~~~~~~~~~~~~~
208+
209+
To learn more about any of the methods or types discussed in this
210+
guide, see the following API documentation:
211+
212+
- `insertOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/insert-one.html>`__
213+
- `insertMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/insert-many.html>`__
214+
- `InsertOneOptions <{+core-api+}/com/mongodb/client/model/InsertOneOptions.html>`__
215+
- `InsertManyOptions <{+core-api+}/com/mongodb/client/model/InsertManyOptions.html>`__
216+
- `InsertOneResult <{+core-api+}/com/mongodb/client/result/InsertOneResult.html>`__
217+
- `InsertManyResult <{+core-api+}/com/mongodb/client/result/InsertManyResult.html>`__
218+
219+
.. .. instruqt::
220+
.. :title: insertOne() Lesson
221+
.. :drawer:

0 commit comments

Comments
 (0)