A simple Java hello world example to works with MongoDB – connect to, create database, collection and document in MongoDB, and also retrieve the saved value and display it to console.

Tools and technologies used :

  1. MongoDB 1.8.1
  2. MongoDB-Java-Driver 2.5.2
  3. JDK 1.6
  4. Maven 3.0.3
  5. Eclipse 3.6

1. Create a Java Project

Create a standard Java project, Maven is the fastest way to do it.

mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mongodb 
	-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2. Get Mongo Java Driver

The mongo-java driver is included in the Maven center repository. To get it, just declares the detail your pom.xml

File : pom.xml

<project ...>
	<dependencies>
 
		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongo-java-driver</artifactId>
			<version>2.5.2</version>
		</dependency>
 
	</dependencies>
</project>
GitHub
Alternatively, you can get the mongo-java driver from – GitHub

3. Hello World

A Java program to work with MongoDB. See comments for explanation.

package com.mkyong.core;
 
import java.net.UnknownHostException;
 
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * Java + MongoDB Hello world Example
 * 
 */
public class App {
	public static void main(String[] args) {
 
		try {
			// connect to mongoDB, ip and port number
			Mongo mongo = new Mongo("localhost", 27017);
 
			// get database from MongoDB,
			// if database doesn't exists, mongoDB will create it automatically
			DB db = mongo.getDB("yourdb");
 
			// Get collection from MongoDB, database named "yourDB"
			// if collection doesn't exists, mongoDB will create it automatically
			DBCollection collection = db.getCollection("yourCollection");
 
			// create a document to store key and value
			BasicDBObject document = new BasicDBObject();
			document.put("id", 1001);
			document.put("msg", "hello world mongoDB in Java");
 
			// save it into collection named "yourCollection"
			collection.insert(document);
 
			// search query
			BasicDBObject searchQuery = new BasicDBObject();
			searchQuery.put("id", 1001);
 
			// query it
			DBCursor cursor = collection.find(searchQuery);
 
			// loop over the cursor and display the retrieved result
			while (cursor.hasNext()) {
				System.out.println(cursor.next());
			}
 
			System.out.println("Done");
 
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
 
	}
}

Output…

{ "_id" : { "$oid" : "4dbe5596dceace565d229dc3"} , 
                "id" : 1001 , "msg" : "hello world mongoDB in Java"}
Done
Download it – mongodb-hello-world.zip (4KB)

Reference

  1. Java tutorial – MongoDB
Note : You can find more similar articles at - Java MongoDB Tutorials