Connect to MongoDB Database in Java using MongoDB Driver Sync

Tags: MongoDB MongoClient MongoClients MongoCollection MongoDatabase Mongo Document Mongo ConnectionString MongoClientSettings

In this Java MongoDB tutorial, we learn how to use MongoDB Drive Sync library to connect to a MongoDB database.

How to add MongoDB Synchronous Driver to your Java project

To use the MongoDB Synchronous Driver Java library in the Gradle build project, add the following dependency into the build.gradle file.

compile group: 'org.mongodb', name: 'mongodb-driver-sync', version: '4.2.0'

To use the MongoDB Synchronous Driver Java library in the Maven build project, add the following dependency into the pom.xml file.

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

To have more information about the MongoDB Synchronous Driver Java library you can visit MongoDB homepage at docs.mongodb.com

Connect to MongoDB with a specified connection string

In the following Java program, we instantiate a new MongoClient object with a given connection string to connect to MongoDB database.

ConnectMongoDBDatabaseExample1.java

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class ConnectMongoDBDatabaseExample1 {
    public static void main(String... args) {
        MongoClient mongoClient = MongoClients.create(
                "mongodb://localhost:27017/?readPreference=primary&appname=SimpleSolution&ssl=false"
        );

        MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("customer");
        Document newCustomer = new Document("firstName", "Emer")
                .append("lastName", "Mullen")
                .append("email", "emer@simplesolution.dev")
                .append("phone", "1234567891");
        mongoCollection.insertOne(newCustomer);

        mongoClient.close();
    }
}

Execute the program above then open MongoDB Compass to observe the new document insert to your database.

Connect to MongoDB Database in Java using MongoDB Driver Sync

Or you can create a ConnectionString object from a given connection string.

ConnectMongoDBDatabaseExample2.java

import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class ConnectMongoDBDatabaseExample2 {
    public static void main(String... args) {
        ConnectionString connectionString = new ConnectionString(
                "mongodb://localhost:27017/?readPreference=primary&appname=SimpleSolution&ssl=false"
        );
        MongoClient mongoClient = MongoClients.create(connectionString);

        MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("customer");
        Document newCustomer = new Document("firstName", "Luci")
                .append("lastName", "Valenzuela")
                .append("email", "luci@simplesolution.dev")
                .append("phone", "1234567892");
        mongoCollection.insertOne(newCustomer);

        mongoClient.close();
    }
}

Execute the program above then open MongoDB Compass to observe the new document insert to your database.

Connect to MongoDB Database in Java using MongoDB Driver Sync

Connect to MongoDB with default connection mongodb://localhost

You can create a new MongoClient object using MongoClients.create() static method without argument which creates a connection to mongodb://localhost .

ConnectMongoDBDatabaseExample3.java

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class ConnectMongoDBDatabaseExample3 {
    public static void main(String... args) {
        MongoClient mongoClient = MongoClients.create();

        MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("customer");
        Document newCustomer = new Document("firstName", "Aaryan")
                .append("lastName", "Bridges")
                .append("email", "aaryan@simplesolution.dev")
                .append("phone", "1234567893");
        mongoCollection.insertOne(newCustomer);

        mongoClient.close();
    }
}

Execute the program above then open MongoDB Compass to observe the new document insert to your database.

Connect to MongoDB Database in Java using MongoDB Driver Sync

Connect to MongoDB with MongoClientSettings

The following Java program to show you how to create a MongoClient from a given MongoClientSettings object.

ConnectMongoDBDatabaseExample4.java

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class ConnectMongoDBDatabaseExample4 {
    public static void main(String... args) {
        ConnectionString connectionString = new ConnectionString(
                "mongodb://localhost:27017/?readPreference=primary&appname=SimpleSolution&ssl=false"
        );
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyConnectionString(connectionString)
                .build();
        MongoClient mongoClient = MongoClients.create(mongoClientSettings);

        MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("customer");
        Document newCustomer = new Document("firstName", "Dean")
                .append("lastName", "Steadman")
                .append("email", "dean@simplesolution.dev")
                .append("phone", "1234567894");
        mongoCollection.insertOne(newCustomer);

        mongoClient.close();
    }
}

Execute the program above then open MongoDB Compass to observe the new document insert to your database.

Connect to MongoDB Database in Java using MongoDB Driver Sync

Happy Coding 😊