Delete MongoDB Document using Kotlin

Introduction

MongoDB is a general-purpose distributed database designed to store data in JSON-like documents. Kotlin is a general-purpose programming language designed to fully interoperate with Java, but uses a type inference that permits its syntax to be much more succinct. Kotlin can handle operations that Java isn’t well suited to and can be successfully used for writing both android and iOS applications, allowing developers to switch between the two platforms. This tutorial will explain how install the Kotlin plugin on the ECLIPSE application and how to delete a MongoDB Document with Kotlin.

Prerequisites

  • The MongoDB server must be properly installed and configured on the system in order to delete a MongoDB Document with Kotlin
  • The ECLIPSE application must be properly installed and configured on the same system.

Installing Kotlin in Eclipse

This section will explain how to install the Kotlin plugin on the ECLIPSE application.

  1. Right click or double click on the ECLIPSE icon to start the ECLIPSE IDE. Now select Open.

  2. Locate and click on the Help button on the menu bar. Select Eclipse Marketplace from its sub-menu. The results should resemble the following:

  1. In the search bar, type Kotlin then press Enter.

  2. Now select the ‘Kotlin Plugin for Eclipse 0.8.19’.

  3. Click on the Install Now - button to execute the installation of the Kotlin plugin.

Downloading MongoDB Java Driver

A compatible driver must be installed to allow Kotlin to interact with the MongoDB server. Follow this link to download the MongoDB Java Driver.

NOTE: The latest version of the MongoDB Java Driver is 3.12.

Adding JAR file to ECLIPSE build path

With the required JAR file downloaded, add the JAR file to the ECLIPSE application by executing the following steps in sequence:

  1. Click on the Project button in the menu bar.
  2. Click on the Propertiesbutton.
  3. Click on Java Build Path button.
  4. Select the Libraries tab.
  5. On the right side panel, click on the Add External JAR... button.
  6. Locate the JAR file downloaded in the previous section.
  7. Finally, click the Apply and Close button to add the JAR file into ECLIPSE application.

Create a MongoDB sample dataset

This section will explain how to create a simple MongoDB dataset for use in this tutorial.

To create the dataset, execute the following command in the MongoDB shell:

switched to db UserDB
> db.user.insert([{name:"risa", lastname:"galisanao"},{name:"joseph", lastname:"tidalgo"},{name:"gina",lastname:"parker"}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.user.find().pretty()
{
        "_id" : ObjectId("5e09778e4ded5acd424f74ea"),
        "name" : "risa",
        "lastname" : "galisanao"
}
{
        "_id" : ObjectId("5e09778e4ded5acd424f74eb"),
        "name" : "joseph",
        "lastname" : "tidalgo"
}
{
        "_id" : ObjectId("5e09778e4ded5acd424f74ec"),
        "name" : "gina",
        "lastname" : "parker"
}
>

Creating a Kotlin Project

With the MongoDB Java driver and a sample MongoDB dataset ready, create the Kotlin project by executing the following steps in order:

  1. Click on File button in the menu bar.
  2. Select New
  3. Select Kotlin Project
  4. Provide a meaningful name for the project in the Project Name text box. For this example, the project name will be kotlinmongo.

Creating a Kotlin Object File

This section will cover how to create a Kotlin object file that will be used for the DELETE operation against the MongoDB Document.

Execute the following steps in order:

  1. Right-click the Kotlin project, kotlinmongo.
  2. Select the New button.
  3. Select the Kotlin Object button.
  4. Provide a meaningful name for the Kotlin Object. For this example name the object KotlinMongoDelete.
  5. Finally, click the Finish button to create the Kotlin file.

Coding the Kotlin MongoDB Delete Operation

This section will create the code that will allow Kotlin to interact with MongoDB.

Open up the KotlinMongoDelete.kt file and append the following codes:

object KotlinMongoDelete {
    @JvmStatic
    fun main(args: Array<String>){
        var mongoClient: MongoClient? = null
        try {
            // mongodb connection
            mongoClient = MongoClient("127.0.0.1", 27017)
            var db = mongoClient.getDB("UserDB")
            var tbl = db.getCollection("user")
           
            // the parameter for searching a document to be deleted
            val searchQry = BasicDBObject();
            searchQry.put("name","risa");
           
            // call the remove method and supply the value for the parameter as the argument
            tbl.remove(searchQry);
           
        } catch (e: MongoException) {
            e.printStackTrace()
        } finally {
            mongoClient!!.close()
        }
    }
   
    data class User(val name: String, val lastname: String)
}

The operation can be verified using the MongoDB shell as follows:

> show dbs
UserDB  0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB
testDB  0.000GB
> use UserDB
switched to db UserDB
> show collections
user
> db.user.find().pretty()
{
        "_id" : ObjectId("5e09778e4ded5acd424f74eb"),
        "name" : "joseph",
        "lastname" : "tidalgo"
}
{
        "_id" : ObjectId("5e09778e4ded5acd424f74ec"),
        "name" : "gina",
        "lastname" : "parker"
}
>

Conclusion

This tutorial explained how to delete a MongoDB document with Kotlin. The article specifically covered the required prerequisite to delete a MongoDB document with Kotlin, how to install Kotlin in Eclipse, download the MongoDB Java driver, add the JAR file to the ECLIPSE build path and how to create a MongoDB sample dataset. The tutorial also explained how to create a Kotlin project, a Kotlin object file and how to set up the code for the Kotlin MongoDB delete operation. Remember that the delete operation can be verified using the MongoDB shell.

The Code

Below is the Kotlin code used in this tutorial.

The KotlinMongoDelete.kt

package kotlinmongo

import com.mongodb.BasicDBObject
import com.mongodb.MongoClient
import com.mongodb.MongoException

object KotlinMongoDelete {
    @JvmStatic
    fun main(args: Array<String>){
        var mongoClient: MongoClient? = null
        try {
            mongoClient = MongoClient("127.0.0.1", 27017)
            var db = mongoClient.getDB("UserDB")
            var tbl = db.getCollection("user")
           
               
            val searchQry = BasicDBObject();
            searchQry.put("name","risa");
           
            tbl.remove(searchQry);
           
        } catch (e: MongoException) {
            e.printStackTrace()
        } finally {
            mongoClient!!.close()
        }
    }
   
    data class User(val name: String, val lastname: String)
}

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.