Connecting to a MongoDB Instance Using KMongo

Got comments?

Often, the seemingly simple things can make you spend hours chasing around your tail. Like trying to connect to a MongoDB instance using KMongo.

Basically, if you have checked out the KMongo quick start, setting up a client and fetching some data should be extremely easy:

val client = KMongo.createClient() //get com.mongodb.MongoClient new instance
val database = client.getDatabase("test") //normal java driver usage
val col = database.getCollection<Jedi>() //KMongo extension method

The quick start tutorial assumes that your DB resides on mongodb://localhost:27017, but in reality, your MongoDB connection string looks more like this:


and in proper production environments, it is unknown until runtime. Let's assume that it was passed to the running application as an environment variable, e.g. MONGODB. Simply passing this string to KMongo.createClient()won't do it. The problem is that KMongo assumes that this string is simply the <HOST> part and creates a ServerAddressout of it. This results in an error when connecting.

The solution is to use a class called MongoClientURIinstead. MongoClientURI parses the string argument and splits it into its corresponding parts.

So, the solution to my problem:

val uri = MongoClientURI(System.getenv("MONGODB"))
val collection = KMongo.createClient(uri = uri)