8000 (DOCSP-29221, DOCSP-29222, DOCSP-29223, DOCSP-29225): Kotlin Data For… · nickldp/docs-kotlin@19dc8aa · GitHub
[go: up one dir, main page]

Skip to content

Commit 19dc8aa

Browse files
authored
1 parent fc0ed78 commit 19dc8aa

27 files changed

+583
-1622
lines changed
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
2+
import com.mongodb.client.model.Filters
3+
import com.mongodb.client.result.InsertOneResult
4+
import com.mongodb.kotlin.client.coroutine.MongoClient
5+
import io.github.cdimascio.dotenv.dotenv
6+
import kotlinx.coroutines.flow.firstOrNull
7+
import kotlinx.coroutines.runBlocking
8+
import org.bson.*
9+
import org.bson.json.JsonObject
10+
import org.bson.types.ObjectId
11+
import org.junit.jupiter.api.AfterAll
12+
import org.junit.jupiter.api.Assertions.*
13+
import org.junit.jupiter.api.TestInstance
14+
import java.time.LocalDate
15+
import java.time.ZoneId
16+
import java.util.*
17+
import kotlin.test.*
18+
19+
20+
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
21+
internal class DocumentsTest {
22+
23+
companion object {
24+
private val dotenv = dotenv()
25+
val mongoClient = MongoClient.create(dotenv["MONGODB_CONNECTION_URI"])
26+
27+
@AfterAll
28+
@JvmStatic
29+
fun afterAll() {
30+
runBlocking {
31+
mongoClient.close()
32+
}
33+
}
34+
}
35+
36+
@Test
37+
fun documentTest() = runBlocking {
38+
// :snippet-start: create-document
39+
val author = Document("_id", ObjectId())
40+
.append("name", "Gabriel García Márquez")
41+
.append(
42+
"dateOfDeath",
43+
Date.from(
44+
LocalDate.of(2014, 4, 17)
45+
.atStartOfDay(ZoneId.systemDefault()).toInstant()
46+
)
47+
)
48+
.append(
49+
"novels", listOf(
50+
Document("title", "One Hundred Years of Solitude").append("yearPublished", 1967),
51+
Document("title", "Chronicle of a Death Foretold").append("yearPublished", 1981),
52+
Document("title", "Love in the Time of Cholera").append("yearPublished", 1985)
53+
)
54+
)
55+
// :snippet-end:
56+
57+
assertNotNull(author)
58+
assertEquals("Gabriel García Márquez", author.getString("name"))
59+
60+
// :snippet-start: insert-document
61+
// val mongoClient = <code to instantiate your client>
62+
63+
val database = mongoClient.getDatabase("fundamentals_data")
64+
val collection = database.getCollection<Document>("authors")
65+
val result = collection.insertOne(author)
66+
// :snippet-end:
67+
68+
assertNotNull(result)
69+
assertEquals(true, result.wasAcknowledged())
70+
71+
// :snippet-start: retrieve-document
72+
val doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).firstOrNull()
73+
doc?.let {
74+
println("_id: ${it.getObjectId("_id")}, name: ${it.getString("name")}, dateOfDeath: ${it.getDate("dateOfDeath")}")
75+
76+
it.getList("novels", Document::class.java).forEach { novel ->
77+
println("title: ${novel.getString("title")}, yearPublished: ${novel.getInteger("yearPublished")}")
78+
}
79+
}
80+
// :snippet-end:
81+
82+
assertNotNull(doc)
83+
assertEquals("Gabriel García Márquez", doc 10000 ?.getString("name"))
84+
assertEquals(3, doc?.getList("novels", Document::class.java)?.size)
85+
86+
// clean up
87+
collection.drop()
88+
}
89+
90+
@Test
91+
fun bsonDocumentTest() = runBlocking {
92+
// :snippet-start: create-bson-document
93+
val author = BsonDocument()
94+
.append("_id", BsonObjectId())
95+
.append("name", BsonString("Gabriel García Márquez"))
96+
.append(
97+
"dateOfDeath",
98+
BsonDateTime(
99+
LocalDate.of(2014, 4, 17)
100+
.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
101+
)
102+
)
103+
.append(
104+
"novels", BsonArray(
105+
listOf(
106+
BsonDocument().append("title", BsonString("One Hundred Years of Solitude"))
107+
.append("yearPublished", BsonInt32(1967)),
108+
BsonDocument().append("title", BsonString("Chronicle of a Death Foretold"))
109+
.append("yearPublished", BsonInt32(1981)),
110+
BsonDocument().append("title", BsonString("Love in the Time of Cholera"))
111+
.append("yearPublished", BsonInt32(1985))
112+
)
113+
)
114+
)
115+
// :snippet-end:
116+
117+
assertNotNull(author)
118+
assertEquals("Gabriel García Márquez", author.getString("name").value)
119+
assertEquals(3, author.getArray("novels").size)
120+
121+
// :snippet-start: insert-bson-document
122+
// val mongoClient = <code to instantiate your client>
123+
124+
val database = mongoClient.getDatabase("fundamentals_data")
125+
val collection = database.getCollection<BsonDocument>("authors")
126+
127+
val result: InsertOneResult = collection.insertOne(author)
128+
// :snippet-end:
129+
130+
assertNotNull(result)
131+
assertEquals(true, result.wasAcknowledged())
132+
133+
// :snippet-start: retrieve-bson-document
134+
// <MongoCollection setup code here>
135+
136+
val doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).firstOrNull()
137+
doc?.let {
138+
println("_id: ${it.getObjectId("_id").value}, name: ${it.getString("name").value}, dateOfDeath: ${Date(it.getDateTime("dateOfDeath").value)}")
139+
140+
it.getArray("novels").forEach { novel ->
141+
val novelDocument = novel.asDocument()
142+
println("title: ${novelDocument.getString("title").value}, yearPublished: ${novelDocument.getInt32("yearPublished").value}")
143+
}
144+
}
145+
// :snippet-end:
146+
147+
assertNotNull(doc)
148+
assertEquals("Gabriel García Márquez", doc?.getString("name")?.value)
149+
assertEquals(3, doc?.getArray("novels")?.size)
150+
151+
// clean up
152+
collection.drop()
153+
}
154+
155+
@Test
156+
fun jsonObjectTest() = runBlocking {
157+
// :snippet-start: create-json-object
158+
val ejsonStr = """
159+
{"_id": {"${"$"}oid": "6035210f35bd203721c3eab8"},
160+
"name": "Gabriel García Márquez",
161+
"dateOfDeath": {"${"$"}date": "2014-04-17T04:00:00Z"},
162+
"novels": [
163+
{"title": "One Hundred Years of Solitude","yearPublished": 1967},
164+
{"title": "Chronicle of a Death Foretold","yearPublished": 1981},
165+
{"title": "Love in the Time of Cholera","yearPublished": 1985}]}
166+
""".trimIndent()
167+
168+
val author = JsonObject(ejsonStr)
169+
// :snippet-end:
170+
171+
assertNotNull(author)
172+
assertEquals("Gabriel García Márquez", author.toBsonDocument().getString("name")?.value)
173+
174+
// :snippet-start: insert-json-object
175+
// val mongoClient = <code to instantiate your client>;
176+
177+
val database = mongoClient.getDatabase("fundamentals_data")
178+
val collection= database.getCollection<JsonObject>("authors")
179+
180+
val result = collection.insertOne(author)
181+
// :snippet-end:
182+
assertNotNull(result)
183+
assertEquals(true, result.wasAcknowledged())
184+
185+
// :snippet-start: retrieve-json-object
186+
// val mongoClient = <code to instantiate your client>;
187+
188+
val query = JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}")
189+
val jsonResult = collection.find(query).firstOrNull()
190+
jsonResult?.let {
191+
println("query result in extended json format: " + jsonResult.json)
192+
}
193+
// :snippet-end:
194+
assertNotNull(jsonResult)
195+
assertEquals("Gabriel García Márquez", jsonResult?.toBsonDocument()?.getString("name")?.value)
196+
197+
// clean up
198+
collection.drop()
199+
}
200+
}

examples/src/test/kotlin/EjsonTest.kt

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
2+
import org.bson.*
3+
import org.bson.json.JsonMode
4+
import org.bson.json.JsonReader
5+
import org.bson.json.JsonWriter
6+
import org.bson.json.JsonWriterSettings
7+
import org.bson.types.ObjectId
8+
import org.junit.jupiter.api.Assertions.*
9+
import org.junit.jupiter.api.TestInstance
10+
import java.io.BufferedWriter
11+
import java.io.OutputStreamWriter
12+
import java.time.Instant
13+
import java.time.ZoneOffset
14+
import java.time.format.DateTimeFormatter
15+
import java.util.*
16+
import kotlin.test.*
17+
18+
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
19+
internal class EjsonTest {
20+
21+
@Test
22+
fun readEjsonDocumentTest() {
23+
// :snippet-start: read-ejson-document
24+
val ejsonStr = """
25+
{ "_id": { "${"$"}oid": "507f1f77bcf86cd799439011"},
26+
"myNumber": {"${"$"}numberLong": "4794261" }}
27+
""".trimIndent()
28+
29+
val doc = Document.parse(ejsonStr)
30+
println(doc)
31+
// :snippet-end:
32+
assertEquals("507f1f77bcf86cd799439011", doc.getObjectId("_id").toString())
33+
}
34+
35+
@Test
36+
fun readEjsonBsonTest() {
37+
// :snippet-start: read-ejson-bson
38+
val ejsonStr = """
39+
{ "_id": { "${"$"}oid": "507f1f77bcf86cd799439011"},
40+
"myNumber": {"${"$"}numberLong": "4794261" }}
41+
""".trimIndent()
42+
43+
val jsonReader = JsonReader(ejsonStr)
44+
45+
jsonReader.readStartDocument()
46+
47+
jsonReader.readName("_id")
48+
val id = jsonReader.readObjectId()
49+
jsonReader.readName("myNumber")
50+
val myNumber = jsonReader.readInt64()
51+
52+
jsonReader.readEndDocument()
53+
54+
println(id.toString() + " is type: " + id.javaClass.name)
55+
println(myNumber.toString() + " is type: " + myNumber.javaClass.name)
56+
57+
jsonReader.close()
58+
// :snippet-end:
59+
assertEquals("507f1f77bcf86cd799439011", id.toString())
60+
}
61+
62+
@Test
63+
fun writeEjsonDocumentTest() {
64+
// :snippet-start: write-ejson-document
65+
val myDoc = Document().append("_id", ObjectId("507f1f77bcf86cd799439012"))
66+
.append("myNumber", 11223344)
67+
68+
val settings = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build()
69+
(myDoc.toJson(settings))
70+
// :snippet-end:
71+
assertEquals(11223344, myDoc.getInteger("myNumber"))
72+
}
73+
74+
// Note: no assertions here since this example is just writing to stdout
75+
@Test
76+
fun writeEjsonBsonTest() {
77+
// :snippet-start: write-ejson-bson
78+
val settings = JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build()
79+
80+
JsonWriter(BufferedWriter(OutputStreamWriter(System.out)), settings).use { jsonWriter ->
81+
jsonWriter.writeStartDocument()
82+
jsonWriter.writeObjectId("_id", ObjectId("507f1f77bcf86cd799439012"))
83+
jsonWriter.writeInt64("myNumber", 11223344)
84+
jsonWriter.writeEndDocument()
85+
jsonWriter.flush()
86+
}
87+
// :snippet-end:
88+
}
89+
90+
@Test
91+
fun customBsonTypeConversionTest() {
92+
// :snippet-start: custom-bson-type-conversion
93+
val settings = JsonWriterSettings.builder()
94+
.outputMode(JsonMode.RELAXED)
95+
.objectIdConverter { value, writer -> writer.writeString(value.toHexString()) }
96+
.dateTimeConverter { value, writer ->
97+
val zonedDateTime = Instant.ofEpochMilli(value).atZone(ZoneOffset.UTC)
98+
writer.writeString(DateTimeFormatter.ISO_DATE_TIME.format(zonedDateTime))
99+
}< 10000 /div>
100+
.build()
101+
102+
val doc = Document()
103+
.append("_id", ObjectId("507f1f77bcf86cd799439012"))
104+
.append("createdAt", Date.from(Instant.ofEpochMilli(1601499609000L)))
105+
.append("myNumber", 4794261)
106+
107+
println(doc.toJson(settings))
108+
// :snippet-end:
109+
assertEquals("507f1f77bcf86cd799439012", doc.getObjectId("_id").toString())
110+
}
111+
112+
}

examples/src/test/kotlin/ExampleMongodbClientTest.kt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
import org.junit.jupiter.api.AfterAll
2-
import org.junit.jupiter.api.Assertions.*
3-
import kotlin.test.*
1+
42
import io.github.cdimascio.dotenv.dotenv
53
import kotlinx.coroutines.runBlocking
64
import org.bson.BsonObjectId
75
import org.bson.Document
8-
import org.bson.BsonType
6+
import org.bson.codecs.pojo.annotations.BsonExtraElements
97
import org.bson.codecs.pojo.annotations.BsonId
10-
import org.bson.codecs.pojo.annotations.BsonProperty
118
import org.bson.codecs.pojo.annotations.BsonIgnore
12-
import org.bson.codecs.pojo.annotations.BsonExtraElements
9+
import org.bson.codecs.pojo.annotations.BsonProperty
10+
import org.junit.jupiter.api.AfterAll
11+
import org.junit.jupiter.api.Assertions.*
1312
import org.junit.jupiter.api.TestInstance
13+
import kotlin.test.*
1414

1515
val dotenv = dotenv()
1616

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
val author = BsonDocument()
2+
.append("_id", BsonObjectId())
3+
.append("name", BsonString("Gabriel García Márquez"))
4+
.append(
5+
"dateOfDeath",
6+
BsonDateTime(
7+
LocalDate.of(2014, 4, 17)
8+
.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
9+
)
10+
)
11+
.append(
12+
"novels", BsonArray(
13+
listOf(
14+
BsonDocument().append("title", BsonString("One Hundred Years of Solitude"))
15+
.append("yearPublished", BsonInt32(1967)),
16+
BsonDocument().append("title", BsonString("Chronicle of a Death Foretold"))
17+
.append("yearPublished", BsonInt32(1981)),
18+
BsonDocument().append("title", BsonString("Love in the Time of Cholera"))
19+
.append("yearPublished", BsonInt32(1985))
20+
)
21+
)
22+
)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
val author = Document("_id", ObjectId())
2+
.append("name", "Gabriel García Márquez")
3+
.append(
4+
"dateOfDeath",
5+
Date.from(
6+
LocalDate.of(2014, 4, 17)
7+
.atStartOfDay(ZoneId.systemDefault()).toInstant()
8+
)
9+
)
10+
.append(
11+
"novels", listOf(
12+
Document("title", "One Hundred Years of Solitude").append("yearPublished", 1967),
13+
Document("title", "Chronicle of a Death Foretold").append("yearPublished", 1981),
14+
Document("title", "Love in the Time of Cholera").append("yearPublished", 1985)
15+
)
16+
)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
val ejsonStr = """
2+
{"_id": {"${"$"}oid": "6035210f35bd203721c3eab8"},
3+
"name": "Gabriel García Márquez",
4+
"dateOfDeath": {"${"$"}date": "2014-04-17T04:00:00Z"},
5+
"novels": [
6+
{"title": "One Hundred Years of Solitude","yearPublished": 1967},
7+
{"title": "Chronicle of a Death Foretold","yearPublished": 1981},
8+
{"title": "Love in the Time of Cholera","yearPublished": 1985}]}
9+
""".trimIndent()
10+
11+
val author = JsonObject(ejsonStr)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// val mongoClient = <code to instantiate your client>
2+
3+
val database = mongoClient.getDatabase("fundamentals_data")
4+
val collection = database.getCollection<BsonDocument>("authors")
5+
6+
val result: InsertOneResult = collection.insertOne(author)

0 commit comments

Comments
 (0)
0