Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MongoDB and Java

DZone's Guide to

MongoDB and Java

· Database Zone ·
Free Resource

Running out of memory? Learn how Redis Enterprise enables large dataset analysis with the highest throughput and lowest latency while reducing costs over 75%! 

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


Running out of memory? Never run out of memory with Redis Enterprise databaseStart your free trial today.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}