Problem:
How to connect to MongoDB 3 from Java? In this post we’ll show how to use MongoDB Java Driver to create Mongo Clients with different options.
MongoDB 3 Java Driver comes with very intuitive API, which we’ll explore in next few posts. In this one we’ll show how to setup Java project, ReplicaSet, and create MongoClient and get a database.
Solution:
Add MongoDB Java Driver as project dependency:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.farenda.java</groupId> <artifactId>mongodb</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>
In the following code we create three instances of MongoClient with different options:
- MongoClient with default connection settings.
- MongoClient connecting using SSL and setting WriteConcern.JOURNALED to confirm writing data.
- MongoClient that will connect to a local replica set.
To setup local ReplicaSet you can use the following script:
mkdir -p /tmp/data/rs1 /tmp/data/rs2 mongod --replSet farenda --logpath "1.log" --dbpath /tmp/data/rs1 --port 7017 --oplogSize 64 --smallfiles --fork mongod --replSet farenda --logpath "2.log" --dbpath /tmp/data/rs2 --port 7018 --oplogSize 64 --smallfiles --fork
And configure nodes from the mongo shell:
config = { _id: "farenda", members: [ { _id : 0, host : "localhost:7017"}, { _id : 1, host : "localhost:7018"} ] }; rs.initiate(config); rs.status();
It’s not needed for one-node Mongo instance, which are usually used for programming. :-)
package com.farenda.mongodb; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.ServerAddress; import com.mongodb.WriteConcern; import com.mongodb.client.MongoDatabase; import java.util.LinkedList; import java.util.List; import static java.util.Arrays.asList; public class MongoConnectionExample { public static void main(String[] args) { defaultConnection(); withSslAndWriteConcern(); connectToReplicaSet(); } private static void defaultConnection() { System.out.println("Creating database with default options."); try (MongoClient client = new MongoClient("localhost")) { List<String> databases = client .listDatabaseNames() .into(new LinkedList<>()); System.out.println("Databases: " + databases); MongoDatabase db = client.getDatabase("test"); displayOptions(db); } } private static void withSslAndWriteConcern() { System.out.println("Creating client with SSL."); MongoClientOptions.Builder builder = MongoClientOptions.builder() .sslEnabled(true) .sslInvalidHostNameAllowed(true) .writeConcern(WriteConcern.JOURNALED); try (MongoClient client = new MongoClient("localhost", builder.build())) { MongoDatabase db = client.getDatabase("test"); displayOptions(db); } } private static void connectToReplicaSet() { System.out.println("Connecting client to replica set."); // Setup nodes first! try (MongoClient client = new MongoClient( asList(new ServerAddress("localhost", 7017), new ServerAddress("localhost", 7018)))) { MongoDatabase db = client.getDatabase("test"); displayOptions(db); } } private static void displayOptions(MongoDatabase db) { System.out.printf("Database read concern: %s, write concern: %s%n%n", db.getReadConcern(), db.getWriteConcern()); } }
The code in straightforward. One thing to note is List<String> list = client.listX().into(new LinkedList<>()), which returns collection of elements from Mongo Driver in given object – here LinkedList. The into(target collection type) is a pattern that you will see a lot in Mongo API.
In the following output you can see that it has successfully connected to databases using different clients:
Creating database with default options. mar 29, 2016 4:33:42 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} mar 29, 2016 4:33:42 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out mar 29, 2016 4:33:42 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:250}] to localhost:27017 mar 29, 2016 4:33:42 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 4]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=6952108} mar 29, 2016 4:33:42 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:251}] to localhost:27017 Databases: [m101, students, school, blog, quartz_mongodb_test, local, test] Database read concern: com.mongodb.ReadConcern@0, write concern: WriteConcern{w=null, wTimeout=null ms, fsync=null, journal=null mar 29, 2016 4:33:42 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:251}] to localhost:27017 because the pool has been closed. Creating client with SSL. mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Database read concern: com.mongodb.ReadConcern@0, write concern: WriteConcern{w=null, wTimeout=null ms, fsync=null, journal=true Connecting client to replica set. mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[localhost:7017, localhost:7018], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Adding discovered server localhost:7017 to client view of cluster mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Adding discovered server localhost:7018 to client view of cluster mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:4, serverValue:9}] to localhost:7017 mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:7017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 4]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=4506819, setName='farenda', canonicalAddress=localhost:7017, hosts=[localhost:7017, localhost:7018], passives=[], arbiters=[], primary='localhost:7017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000001, setVersion=1} mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Discovered cluster type of REPLICA_SET mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Setting max election id to 7fffffff0000000000000001 from replica set primary localhost:7017 Database read concern: com.mongodb.ReadConcern@0, write concern: WriteConcern{w=null, wTimeout=null ms, fsync=null, journal=null mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Setting max set version to 1 from replica set primary localhost:7017 mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:5, serverValue:5}] to localhost:7018 mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Discovered replica set primary localhost:7017 mar 29, 2016 4:33:44 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:7018, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 4]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=2308274, setName='farenda', canonicalAddress=localhost:7018, hosts=[localhost:7017, localhost:7018], passives=[], arbiters=[], primary='localhost:7017', tagSet=TagSet{[]}, electionId=null, setVersion=1}
In the next post we’ll explore MongoDB 3 API.