Over a million developers have joined DZone.
Platinum Partner

MongoDB and Java

· Database Zone

The Database Zone is brought to you in partnership with Delphix.  Speed up your development and test cycles with fully automated data delivery, view a 10 minute demo.

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...


The Database Zone is brought to you in partnership with Delphix. Learn how you can easily virtualize and clone your database, read the white paper.

Topics:

Published at DZone with permission of Moshe Kaplan , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}