1
1
import com.mongodb.*
2
2
import com.mongodb.client.ClientSession
3
3
import com.mongodb.client.MongoClients
4
- import com.mongodb.client.MongoCollection
5
4
import org.bson.Document
6
5
6
+ // start-data-class
7
+ data class Restaurant (val name : String , val cuisine : String )
8
+ // end-data-class
9
+
7
10
fun main () {
8
11
// start-transaction
9
12
// Creates a new MongoClient with a connection string
10
13
val client = MongoClients .create(" <connection string>" )
11
14
12
15
// Gets the database and collection
13
- val restaurantsDb = client.getDatabase(" sample_restaurants" )
14
- val restaurantsCollection : MongoCollection < Document > = restaurantsDb .getCollection(" restaurants" )
16
+ val database = client.getDatabase(" sample_restaurants" )
17
+ val collection = database .getCollection< Restaurant > (" restaurants" )
15
18
16
- fun insertDocuments (session : ClientSession ) {
19
+ // Defines options and inserts restaurants into the collection
20
+ fun insertRestaurantsInTransaction (session : ClientSession ) {
17
21
// Sets options for the collection operation within the transaction
18
- val restaurantsCollectionWithOptions = restaurantsCollection
22
+ val restaurantsCollectionWithOptions = collection
19
23
.withWriteConcern(WriteConcern (" majority" ))
20
24
.withReadConcern(ReadConcern .LOCAL )
21
25
22
- // Inserts documents within the transaction
26
+ // Inserts restaurants within the transaction
23
27
restaurantsCollectionWithOptions.insertOne(
24
28
session,
25
- Document (" name" , " Kotlin Sync Pizza" ).append(" cuisine" , " Pizza" )
29
+ Restaurant (" name" , " Kotlin Sync Pizza" ).append(" cuisine" , " Pizza" )
26
30
)
27
31
restaurantsCollectionWithOptions.insertOne(
28
32
session,
29
- Document (" name" , " Kotlin Sync Burger" ).append(" cuisine" , " Burger" )
33
+ Restaurant (" name" , " Kotlin Sync Burger" ).append(" cuisine" , " Burger" )
30
34
)
31
35
}
32
36
@@ -40,7 +44,7 @@ fun main() {
40
44
41
45
// Uses the withTransaction method to start a transaction and run the given function
42
46
session.withTransaction({
43
- insertDocuments (session)
47
+ insertRestaurantsInTransaction (session)
44
48
println (" Transaction succeeded" )
45
49
}, txnOptions)
46
50
} catch (e: Exception ) {
0 commit comments