How do I connect to a MongoDB Database?

In the previous post you have seen how we installed the MongoDB database server and try to use the MongoDB shell to manipulate collections in the database. You also have been introduced how to obtain and setup the MongoDB Java Driver that we can use to manipulate the MongoDB database from a Java program.

Starting from this post we will begin to explore more on how to use the power of MongoDB Java Driver to work with MongoDB. You will see how we are connecting to the database, how to do a CRUD operation (Create, Read, Update and Delete) with Java Driver. But first let see how we create a connection to a database in MongoDB.

Here is our first code snippet, it shows you how to bootstrap the MongoDB to open a connection to a database.

package org.kodejava.mongodb;

import com.mongodb.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Random;

public class MongoDBConnect {
    public static void main(String[] args) {
        MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

        MongoDatabase db = client.getDatabase("school");
        MongoCollection<Document> students = db.getCollection("students");
        students.deleteMany(new BasicDBObject());

        String[] types = {"Homework", "Quiz", "Essay"};
        for (int i = 1; i <= 10; i++) {
            for (int j = 0; j < 3; j++) {
                students.insertOne(new Document("student_id", i)
                        .append("type", types[j])
                        .append("score", new Random().nextInt(100)));
            }
        }

        FindIterable<Document> documents = students.find();
        for (Document document : documents) {
            System.out.println(document.toJson());
        }
    }
}

What you can see from the code above is. First we bootstrap the MongoDB by create an instance of MongoClient. Here we pass a ServerAddress to define the address of our MongoDB database with information about the host name and the port number. If you just create an instance of MongoClient without any arguments it will use the default address such as localhost for the host and 27017 as the default port number.

MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

After initialize the MongoClient we can connect to a database by calling the getDatabase() method and passing the database name as argument. In the example above we connect to the school database, the database in MongoDB is represented by the MongoDatabase class in the com.mongodb.client package. In the next line after connected to the database you can see that we are getting the students collection from this database. Just for the purpose of this example we then empty the students collection using the deleteMany() method of the MongoCollection class.

MongoDatabase db = client.getDatabase("school");
MongoCollection<Document> students = db.getCollection("students");
students.deleteMany(new BasicDBObject());

In the next lines until the end of a code snippet you can see that we populate some random data into the students collections. We call the MongoCollection.insertOne() method to insert documents into the students collection. And finally we read the inserted documents from the students collection using the find() method and iterate the returned documents one by one until all documents printed on the console.

String[] types = {"Homework", "Quiz", "Essay"};
for (int i = 1; i <= 10; i++) {
    for (int j = 0; j < 3; j++) {
        students.insertOne(new Document("student_id", i)
                .append("type", types[j])
                .append("score", new Random().nextInt(100)));
    }
}

FindIterable<Document> documents = students.find();
for (Document document : documents) {
    System.out.println(document.toJson());
}

And here are the sample of the result produced by our code above.

{"_id": {"$oid": "61911c793ae3117f6a5080a1"}, "student_id": 1, "type": "Homework", "score": 31}
{"_id": {"$oid": "61911c793ae3117f6a5080a2"}, "student_id": 1, "type": "Quiz", "score": 93}
{"_id": {"$oid": "61911c793ae3117f6a5080a3"}, "student_id": 1, "type": "Essay", "score": 92}
{"_id": {"$oid": "61911c793ae3117f6a5080a4"}, "student_id": 2, "type": "Homework", "score": 88}
{"_id": {"$oid": "61911c793ae3117f6a5080a5"}, "student_id": 2, "type": "Quiz", "score": 65}
{"_id": {"$oid": "61911c793ae3117f6a5080a6"}, "student_id": 2, "type": "Essay", "score": 64}
{"_id": {"$oid": "61911c793ae3117f6a5080a7"}, "student_id": 3, "type": "Homework", "score": 48}
{"_id": {"$oid": "61911c793ae3117f6a5080a8"}, "student_id": 3, "type": "Quiz", "score": 77}
{"_id": {"$oid": "61911c793ae3117f6a5080a9"}, "student_id": 3, "type": "Essay", "score": 20}
{"_id": {"$oid": "61911c793ae3117f6a5080aa"}, "student_id": 4, "type": "Homework", "score": 36}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.12.11</version>
    </dependency>
</dependencies>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.