MongoClient mongoClient = new MongoClient();
MongoClient mongoClient = new MongoClient("localhost");Or:
MongoClient mongoClient = new MongoClient("db1.server.com");
MongoClient mongoClient = new MongoClient("localhost", 27017);Or:
MongoClient mongoClient = new MongoClient("db1.server.com", 27018);
List<ServerAddress> seeds = new ArrayList<ServerAddress>(); seeds.add(new ServerAddress("db1.server.com", 27017)); seeds.add(new ServerAddress("db2.server.com", 27018)); seeds.add(new ServerAddress("db3.server.com", 27019)); MongoClient mongoClient = new MongoClient(seeds);After the connection is established, we can obtain a database and make authentication (if the server is running in secure mode), for example:
MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("test"); char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'}; boolean authenticated = db.authenticate("root", password); if (authenticated) { System.out.println("Successfully logged in to MongoDB!"); } else { System.out.println("Invalid username/password"); }By default, MongoDB server is running in trusted mode which doesn’t require authentication.
package net.codejava.mongodb; import java.net.UnknownHostException; import java.util.List; import java.util.Set; import com.mongodb.DB; import com.mongodb.MongoClient; public class JavaMongoDBConnection { public static void main(String[] args) { try { MongoClient mongoClient = new MongoClient("localhost"); List<String> databases = mongoClient.getDatabaseNames(); for (String dbName : databases) { System.out.println("- Database: " + dbName); DB db = mongoClient.getDB(dbName); Set<String> collections = db.getCollectionNames(); for (String colName : collections) { System.out.println("\t + Collection: " + colName); } } mongoClient.close(); } catch (UnknownHostException ex) { ex.printStackTrace(); } } }This Java program connects to a MongoDB server running on localhost at default port, then lists all database names available on the server. For each database, it lists all collection names (a collection is equivalent to a table in relational database), and finally closes the connection. This program would produce the following output:
- Database: local
+ Collection: startup_log
- Database: mydb
+ Collection: system.indexes
+ Collection: things
- Database: test
+ Collection: system.indexes
+ Collection: test
String dbURI = "mongodb://localhost"; MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI));Syntax of the URI is as follows:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
Here are some connection string URI examples:mongodb://localhost
mongodb://root:secret@db1.server.com:27027
mongodb://db2.server.com/users
mongodb://tom:secret@db3.server.com:27027/products
mongodb://db1.server.com,db2.server.com,db3.server.com
See detailed information about MongoDB’s connection string URI.To see the coding in action, I recommend you to watch this video: