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

Databases are better when they can run themselves. CockroachDB is a SQL database that automates scaling and recovery. Check it out here.

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


Databases should be easy to deploy, easy to use, and easy to scale. If you agree, you should check out CockroachDB, a scalable SQL database built for businesses of every size. Check it out here. 

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