1
+ import com.mongodb.kotlin.client.MongoClient
2
+ import org.bson.Document
3
+ import com.mongodb.event.*
4
+ import com.mongodb.MongoClientSettings
5
+ import com.mongodb.ConnectionString
6
+
7
+ class CommandCounter : CommandListener {
8
+ private val commands = mutableMapOf<String , Int >()
9
+
10
+ override fun commandSucceeded (event : CommandSucceededEvent ) {
11
+ val commandName = event.commandName
12
+ val count = commands[commandName] ? : 0
13
+ commands[commandName] = count + 1
14
+ println (commands.toString())
15
+ }
16
+
17
+ override fun commandFailed (event : CommandFailedEvent ) {
18
+ println (" Failed execution of command '${event.commandName} ' with id ${event.requestId} " )
19
+ }
20
+ }
21
+
22
+
23
+ fun main () {
24
+ val uri = " <connection string uri>"
25
+
26
+ // Instantiate your new listener
27
+ val commandCounter = CommandCounter ()
28
+
29
+ // Include the listener in your client settings
30
+ val settings = MongoClientSettings .builder()
31
+ .applyConnectionString(ConnectionString (uri))
32
+ .addCommandListener(commandCounter)
33
+ .build()
34
+
35
+ // Connect to your database
36
+ val mongoClient = MongoClient .create(settings)
37
+ val database = mongoClient.getDatabase(" sample_mflix" )
38
+ val collection = database.getCollection<Document >(" movies" )
39
+
40
+ // Run some commands to test the counter
41
+ collection.find().firstOrNull()
42
+ collection.find().firstOrNull()
43
+
44
+ mongoClient.close()
45
+ }
0 commit comments