NoSQL Zone is brought to you in partnership with:

' ! Moshe Kaplan constantly helps successful firms getting to the next level and he is thrilled to uncover some of his secrets. Mr. Kaplan is a seasoned project management and cloud technologies lecturer. He is also known to be a cloud and SCRUM evangelist Moshe is a dSero.com Co-Founder. He was a R&D Director at Essence Security, led RockeTier and served as a board member in the IGT and as a department head at a top IDF IT unit. Moshe holds M.Sc and B.Sc from TAU. Moshe is a DZone MVB and is not an employee of DZone and has posted 59 posts at DZone. You can read more from them at their website. View Full User Profile

MongoDB and Java

06.26.2013
| 4144 views |
  • submit to reddit

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 driverCompiling 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 LineJava and MongoDB integration is not too difficult, you just need to do the right thinks right...

Published at DZone with permission of Moshe Kaplan, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)