Jun 25, 2013

MongoDB and Java

You can find below some hints for initial Java and MongoDB integration

Take a Look at the Requirements
  1. MongoDB
  2. MongoDB-Java-Driver
  3. JDK. If you want use JDK 1.6 or newer, you will get an error like this one: "DBObject cannot be resolved to a type"
Installing Java
yum -y install java-1.7.0-openjdk
yum -y install java-1.7.0-openjdk-devel

Getting MongoDB driver

Compiling Java
javac -d . *.java
java -cp . com/example/mbeans/Main

Define MongoDB Headers in the Code
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import com.mongodb.*;

Connect to MongoDB
DB _db;

public void init() {
try {
System.out.println("Connecting to mongo...");
MongoClient mongoClient = new MongoClient("127.0.0.1" , 27017);
_db = mongoClient.getDB("display");
System.out.println("Connected to mongo...");
} catch (Exception e) {
System.out.println("Failed Connecting Mongo...");
}

Query the Database (Get the Number of Connections)
CommandResult stats = _db.command("serverStatus");
return Integer.valueOf((((DBObject)(stats.get("connections"))).get("current")).toString());

Bottom Line
Java and MongoDB integration is not too difficult, you just need to do the right thinks right...

Keep Performing,

ShareThis

Intense Debate Comments

Ratings and Recommendations