MongoDB connectivity with Vert.x

Reading Time: 2 minutes

MongoDB is an open-source document database and leading NoSQL database. Instead of using tables and rows as in the traditional relational databases, it makes use of collections and documents. Documents consist of key-value pairs which are the basic unit of data in MongoDB.

mongodb documents structure

Connect to MongoDB

To connect first you need to make sure that you have MongoDB client.

A Vert.x client allowing applications to interact with a MongoDB instance, whether that’s saving, retrieving, searching, or deleting documents. Mongo is a great match for persisting data in a Vert.x application as it natively handles JSON (BSON) documents.

Create a database in your mongoDB and a collection. If the database doesn’t exist then MongoDB creates it automatically.

Vert.x MongoDB Client

Before you start using MongoDB you need to add the add the following dependency to get started with mongoDB.

  • For Maven project (in your pom.xml):
<dependency>
 <groupId>io.vertx</groupId>
 <artifactId>vertx-mongo-client</artifactId>
 <version>4.2.6</version>
</dependency>
  • For Gradle project (in your build.gradle file):
compile 'io.vertx:vertx-mongo-client:4.2.6'

Creating a client

We can create a client in several ways, here we created a client with a non shared data pool.

In most cases you will want to share a pool between different client instances. However, it’s possible you want to create a client instance that doesn’t share its pool with any other client. For example:

MongoClient mongoClient = MongoClient.create(vertx, new JsonObject()
        .put("url", <DATABASE URL>)
        .put("db_name", <YOUR DATABASE NAME>));

Now we can use this client to perform CRUD operations such as find, insert, update and delete the documents.

Inserting documents

To insert a document we use insert() method.

If the document is inserted and has no id, then the id field generated will be returned to the result handler. for example:

JsonObject document = new JsonObject()
  .put("name", "Aasif");
mongoClient.insert("students", document, res -> {
  if (res.succeeded()) {
    String id = res.result();
    System.out.println("Inserted student with id " + id);
  } else {
    res.cause().printStackTrace();
  }
});

Updating documents

To update a documents we use updateCollecttion() method.

This updates one or multiple documents in a collection. The json object that is passed in the updateCollection parameter must contain Update Operators and determines how the object is updated.

The json object specified in the query parameter determines that which documents in the collection will be updated. for example:

JsonObject query = new JsonObject()
  .put("name", "Aasif");
// Set the course field
JsonObject update = new JsonObject().put("$set", new JsonObject()
  .put("course", "MCA"));
mongoClient.updateCollection("students", query, update, res -> {
  if (res.succeeded()) {
    System.out.println("Student updated !");
  } else {
    res.cause().printStackTrace();
  }
});

Finding documents

To find documents you use find() method.

The query parameter is used to match the documents in the collection. To find all the students in the collection. For example with an empty query that will match all students:

JsonObject query = new JsonObject();
mongoClient.find("students", query, res -> {
  if (res.succeeded()) {
    for (JsonObject json : res.result()) {
      System.out.println(json.encodePrettily());
    }
  } else {
    res.cause().printStackTrace();
  }
});

Find a student by Id for example :

JsonObject query = new JsonObject()
  .put("id", "6233284ae1e27a1ee9385e1d");
mongoClient.find("students", query, res -> {
  if (res.succeeded()) {
    for (JsonObject json : res.result()) {
      System.out.println(json.encodePrettily());
    }
  } else {
    res.cause().printStackTrace();
  }
});

Matching documents returned as a list of json objects in the result handler.

knoldus

Written by 

Aasif Ali is a Software Consultant at Knoldus Inc. He has done Post Graduation from Quantum University Roorkee. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is a quick learner, problem solver and always enjoy to help others. His hobbies are watching Sci-fi movies , Playing badminton and listening to songs.