Skip to content

Commit a708aa6

Browse files
authored
(DOCSP-29219): CRUD > Insert Operations page (#11)
* (DOCSP-29219): CRUD > Insert page * Update tests * Fix failing InsertManyTest * Apply tech review feedback * Apply initiial internal review feedback * Refactor tests * Refactor to use only one data class * add io block * Convert to Flow.collect { }
1 parent 19918de commit a708aa6

File tree

7 files changed

+167
-44
lines changed

7 files changed

+167
-44
lines changed

examples/build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ dependencies {
1515
testImplementation(kotlin("test"))
1616
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.0-Beta")
1717
implementation("org.mongodb:mongodb-driver-kotlin-coroutine:4.10.0-SNAPSHOT")
18+
implementation("org.mongodb:mongodb-driver-core:4.10.0-SNAPSHOT")
1819
implementation("org.slf4j:slf4j-api:1.7.32")
1920
implementation("ch.qos.logback:logback-classic:1.2.6")
2021
implementation("io.github.cdimascio:dotenv-kotlin:6.4.1")
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
2+
3+
import com.mongodb.MongoBulkWriteException
4+
import com.mongodb.kotlin.client.coroutine.MongoClient
5+
import io.github.cdimascio.dotenv.dotenv
6+
import kotlinx.coroutines.flow.toList
7+
import kotlinx.coroutines.runBlocking
8+
import org.bson.codecs.pojo.annotations.BsonId
9+
import org.bson.types.ObjectId
10+
import org.junit.jupiter.api.AfterAll
11+
import org.junit.jupiter.api.Assertions.*
12+
import org.junit.jupiter.api.TestInstance
13+
import java.util.*
14+
import kotlin.test.*
15+
16+
// :snippet-start: data-model
17+
data class PaintOrder(
18+
@BsonId val id: ObjectId? = null,
19+
val qty: Int,
20+
val color: String
21+
)
22+
// :snippet-end:
23+
24+
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
25+
internal class InsertTest {
26+
27+
companion object {
28+
val dotenv = dotenv()
29+
val client = MongoClient.create(dotenv["MONGODB_CONNECTION_URI"])
30+
val database = client.getDatabase("paint_store")
31+
val collection = database.getCollection<PaintOrder>("paint_order")
32+
33+
@AfterAll
34+
@JvmStatic
35+
private fun afterAll() {
36+
runBlocking {
37+
client.close()
38+
}
39+
}
40+
}
41+
@Test
42+
fun insertManyErrorTest() = runBlocking {
43+
val paintOrders = listOf(
44+
PaintOrder(ObjectId(), 5, "red"),
45+
PaintOrder(ObjectId(), 10, "purple"),
46+
PaintOrder(ObjectId(), 3, "yellow"),
47+
PaintOrder(ObjectId(), 8, "blue")
48+
)
49+
// :snippet-start: insert-many-error
50+
val result = collection.insertMany(paintOrders)
51+
try {
52+
println("Inserted documents with the following ids: ${result.insertedIds}")
53+
} catch(e: MongoBulkWriteException){
54+
val insertedIds = e.writeResult.inserts.map { it.id.asInt32().value }
55+
println(
56+
"A MongoBulkWriteException occurred, but there are " +
57+
"successfully processed documents with the following ids: $insertedIds"
58+
)
59+
collection.find().collect { println(it) }
60+
}
61+
// :snippet-end:
62+
//Junit test for the above code
63+
assertTrue(result.wasAcknowledged())
64+
}
65+
66+
@Test
67+
fun insertOneTest() = runBlocking {
68+
// :snippet-start: insert-one
69+
val paintOrder = PaintOrder(ObjectId(), 5, "red")
70+
val result = collection.insertOne(paintOrder)
71+
72+
val insertedId = result.insertedId?.asObjectId()?.value
73+
74+
println("Inserted a document with the following id: $insertedId")
75+
// :snippet-end:
76+
// Junit test for the above code
77+
assertTrue(result.wasAcknowledged())
78+
}
79+
80+
@Test
81+
fun insertManyTest() = runBlocking {
82+
// :snippet-start: insert-many
83+
val paintOrders = listOf(
84+
PaintOrder(ObjectId(), 5, "red"),
85+
PaintOrder(ObjectId(), 10, "purple")
86+
)
87+
val result = collection.insertMany(paintOrders)
88+
89+
println("Inserted a document with the following ids: ${result.insertedIds.toList()}")
90+
// :snippet-end:
91+
// Junit test for the above code
92+
assertTrue(result.wasAcknowledged())
93+
}
94+
}
95+
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
data class PaintOrder(
2+
@BsonId val id: ObjectId? = null,
3+
val qty: Int,
4+
val color: String
5+
)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
val result = collection.insertMany(paintOrders)
2+
try {
3+
println("Inserted documents with the following ids: ${result.insertedIds}")
4+
} catch(e: MongoBulkWriteException){
5+
val insertedIds = e.writeResult.inserts.map { it.id.asInt32().value }
6+
println(
7+
"A MongoBulkWriteException occurred, but there are " +
8+
"successfully processed documents with the following ids: $insertedIds"
9+
)
10+
collection.find().collect { println(it) }
11+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
val paintOrders = listOf(
2+
PaintOrder(ObjectId(), 5, "red"),
3+
PaintOrder(ObjectId(), 10, "purple")
4+
)
5+
val result = collection.insertMany(paintOrders)
6+
7+
println("Inserted a document with the following ids: ${result.insertedIds.toList()}")
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
val paintOrder = PaintOrder(ObjectId(), 5, "red")
2+
val result = collection.insertOne(paintOrder)
3+
4+
val insertedId = result.insertedId?.asObjectId()?.value
5+
6+
println("Inserted a document with the following id: $insertedId")

source/fundamentals/crud/write-operations/insert.txt

Lines changed: 42 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Insert Operations
1515
Overview
1616
--------
1717

18-
In this guide, you can learn how to insert documents with the MongoDB Java
18+
In this guide, you can learn how to insert documents with the MongoDB Kotlin
1919
driver.
2020

2121
You can use MongoDB to retrieve, update, and delete information. To
@@ -32,6 +32,12 @@ The following sections focus on ``insertOne()`` and
3232
method, see our
3333
:doc:`guide on Bulk Operations </fundamentals/crud/write-operations/bulk/>`.
3434

35+
In the following examples, a paint store has an inventory of different colors
36+
of paint. This data is modeled with the following Kotlin data class:
37+
38+
.. literalinclude:: /examples/generated/InsertTest.snippet.data-model.kt
39+
:language: kotlin
40+
3541
A Note About ``_id``
3642
--------------------
3743

@@ -70,24 +76,21 @@ Example
7076
The following example creates and inserts a document using the
7177
``insertOne()`` method:
7278

73-
.. literalinclude:: /includes/fundamentals/code-snippets/Insert.java
74-
:language: java
75-
:dedent:
76-
:start-after: begin insertOneExample
77-
:end-before: end insertOneExample
78-
79-
Your output should look something like this:
79+
.. io-code-block::
80+
81+
.. input:: /examples/generated/InsertTest.snippet.insert-one.kt
82+
:language: kotlin
8083

81-
.. code-block:: none
82-
:copyable: false
84+
.. output::
85+
:language: console
8386

84-
Inserted a document with the following id: 60930c39a982931c20ef6cd6
87+
Inserted a document with the following id: 60930c39a982931c20ef6cd6
8588

8689
For more information about the methods and classes mentioned in this section,
8790
see the following resources:
8891

89-
- `insertOne() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertOne(TDocument)>`__ API Documentation
90-
- `InsertOneResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertOneResult.html>`__ API Documentation
92+
- `insertOne() <TODO:(DOCSP-29169)>`__ API Documentation
93+
- `InsertOneResult <TODO:(DOCSP-29169)>`__ API Documentation
9194
- Manual Explanation on :manual:`insertOne() </reference/method/db.collection.insertOne/>`
9295
- Runnable :doc:`Insert a Document Example </usage-examples/insertOne>`
9396

@@ -102,10 +105,10 @@ For example, assume you want to insert the following documents:
102105

103106
.. code-block:: json
104107

105-
{ "_id": 3, "color": "red", "qty": 5 }
106-
{ "_id": 4, "color": "purple", "qty": 10 }
107-
{ "_id": 3, "color": "yellow", "qty": 3 }
108-
{ "_id": 6, "color": "blue", "qty": 8 }
108+
{ "color": "red", "qty": 5 }
109+
{ "color": "purple", "qty": 10 }
110+
{ "color": "yellow", "qty": 3 }
111+
{ "color": "blue", "qty": 8 }
109112

110113
If you attempt to insert these documents, a ``WriteError`` occurs at the
111114
third document and the documents prior to the error get inserted into
@@ -114,30 +117,28 @@ your collection.
114117
.. tip::
115118

116119
Use a try-catch block to get an acknowledgment for successfully
117-
processed documents before the error occurs:
120+
processed documents before the error occurs. The output consists of
121+
documents MongoDB can process:
118122

119-
.. literalinclude:: /includes/fundamentals/code-snippets/Insert.java
120-
:language: java
121-
:dedent:
122-
:start-after: begin insertManyErrorExample
123-
:end-before: end insertManyErrorExample
123+
.. io-code-block::
124+
125+
.. input:: /examples/generated/InsertTest.snippet.insert-many-error.kt
126+
:language: kotlin
124127

125-
The output consists of documents MongoDB can process and should look
126-
something like this:
128+
.. output::
129+
:language: console
127130

128-
.. code-block::
129-
:copyable: false
130-
131-
A MongoBulkWriteException occurred, but there are successfully processed
132-
documents with the following ids: [3, 4, 6]
131+
A MongoBulkWriteException occurred, but there are successfully processed
132+
documents with the following ids: [60930c3aa982931c20ef6cd7, 644ad1378ea29443837a14e9, 60930c3aa982931c20ef6cd8]
133+
133134

134135
If you look inside your collection, you should see the following documents:
135136

136137
.. code-block:: json
137138
:copyable: false
138139

139-
{ "_id": 3, "color": "red", "qty": 5 }
140-
{ "_id": 4, "color": "purple", "qty": 10 }
140+
{ "color": "red", "qty": 5 }
141+
{ "color": "purple", "qty": 10 }
141142

142143
On successful insertion, the method returns an ``InsertManyResult``
143144
instance representing the ``_id`` of each new document.
@@ -148,24 +149,21 @@ Example
148149
The following example creates and adds two documents to a ``List``, and
149150
inserts the ``List`` using the ``insertMany()`` method:
150151

151-
.. literalinclude:: /includes/fundamentals/code-snippets/Insert.java
152-
:language: java
153-
:dedent:
154-
:start-after: begin insertManyExample
155-
:end-before: end insertManyExample
156-
157-
Your output should look something like this:
152+
.. io-code-block::
153+
154+
.. input:: /examples/generated/InsertTest.snippet.insert-many.kt
155+
:language: kotlin
158156

159-
.. code-block::
160-
:copyable: false
157+
.. output::
158+
:language: console
161159

162-
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]
160+
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]
163161

164162
For more information about the methods and classes mentioned in this section,
165163
see the following resources:
166164

167-
- `insertMany() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html#insertMany(java.util.List)>`__ API Documentation
168-
- `InsertManyResult <{+api+}/apidocs/mongodb-driver-core/com/mongodb/client/result/InsertManyResult.html>`__ API Documentation
165+
- `insertMany() <TODO:(DOCSP-29169)>`__ API Documentation
166+
- `InsertManyResult <TODO:(DOCSP-29169)>`__ API Documentation
169167
- Manual Explanation on :manual:`insertMany() </reference/method/db.collection.insertMany/>`
170168
- Runnable :doc:`Insert Multiple Documents Example </usage-examples/insertMany>`
171169

0 commit comments

Comments
 (0)