MongoDB Java driver testing

1. Install latest JDK(jdk-8u5-linux-x64.rpm)
2. Download MongoDB Java driver(mongo-java-driver-2.12.1.jar)
3. Export the variables / run the program in the below given format by keeping jar file in the same folder.
3. Run the java code

example code;-

[root@myhostname JAVA]$ cat jdriver.java
import java.util.Set;
import java.util.Arrays;
import java.net.UnknownHostException;
import com.mongodb.*;

class jdriver{
public static void main(String[] args) {

try {
//Initial connection to the mongodb
MongoClientURI uri = new MongoClientURI(“mongodb://username:password@xxx.xxx.xxx.xxx:port/database”);
MongoClient client = new MongoClient(uri);
DB db = client.getDB(uri.getDatabase());

//Retrieving the list of collection names
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}

}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (MongoException e) {
e.printStackTrace();
}
}
}

[root@myhostname JAVA]$ pwd
/home/srini/JAVA
[root@myhostname JAVA]$ ls
mongo-java-driver-2.12.1.jar jdk-8u5-linux-x64.rpm jdriver.java

[root@myhostname JAVA]$ javac -cp .:mongo-java-driver-2.12.1.jar jdriver.java
[root@myhostname JAVA]$ java -cp .:mongo-java-driver-2.12.1.jar jdriver
people
system.indexes
system.users

  • Ask Question