A simple Kotlin class to use to connect to a MongoDB collection

mongodb-kotlin

A simple Kotlin class to use to connect to a MongoDB collection.

Once you have created a MongoDB project, choose Build a Database:

Next, choose the free “Shared” option and scroll all the way down:

Expand “Cluster Name” and pick a cool name for your cluster. I’ll leave it as the default.
Now, we need to create a seperate username and password so our code can access this database.

Click create user once you’re done and be sure to select Cloud Environment as your connection location.

Lastly, add “0.0.0.0/0” as an IP Address.

At the bottom, click Finish and Close.
Once it’s ready, click Browse Collections and Add My Own Data.

You’ll need to pick a name for your database and it’s collection. Don’t forget them.
Now click overview and then CONNECT:


Choose Connect your application:

All you will need from this is the bit of text from the “@” symbol to where it says “mongodb.net” (it should look like “clusterName.random stuff”):

Now you’re ready to write some code.

When you create an instance of the MongoDB class, put in the username and password we just made:

MongoDB(LoginInfo("myUsername", "mySecurePassword"), "cluster", "MyDatabaseName")

“cluster” is that string we found in the very last step.
“MyDatabaseName” is the one you chose along with the collection name.
Check the Example.kt for more information.

Note

At the time of writing, the correct pom dependancy for Maven is (the version may change in the future):

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.4.0</version>
</dependency>

GitHub

View Github