How to Query MongoDB in Java Program

How to Query MongoDB in Java

In this example, We will show you simple program about, How to query mongodb in Java. The sample program were tested with environment and output has been shared in the same post.

Insert Documents

Before going to query MongoDB in Java, make sure you have some records available in database (ie: MongoDB). We have given sample documents below you can insert the same to mongodb server.

/* 1 */
{
    "_id" : 101,
    "name" : "John",
    "designation" : "Software Engineer"
}

/* 2 */
{
    "_id" : 102,
    "name" : "Dinesh",
    "designation" : "Sr. Software Engineer"
}

/* 3 */
{
    "_id" : 103,
    "name" : "Smith",
    "designation" : "Project Manager"
}

/* 4 */
{
    "_id" : 104,
    "name" : "William",
    "designation" : "Software Engineer"
}

/* 5 */
{
    "_id" : 105,
    "name" : "James",
    "designation" : "Business Analyst"
}

Once the document inserted successfully. You can query and check the database whether its available or not.

How to Query MongoDB in Java

Example Program

package com.dineshkrish.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class GetDocument {

	public static void main(String[] args) {

		// host name
		final String HOST_NAME = "localhost";

		// default port number
		final int PORT = 27017;

		// creating mongo client object
		MongoClient client = new MongoClient(HOST_NAME, PORT);

		// selecting the mongo database
		MongoDatabase database = client.getDatabase("dineshkrish");

		// selecting the mongo collection
		MongoCollection<Document> collection = database
				.getCollection("employee_records");

		// preparing query document
		Document query = new Document();

		query.put("_id", 102);

		// selecting the document
		FindIterable<Document> result = collection.find(query);
		
		// preparing for an iteration
		MongoCursor<Document> cursor = result.iterator();
		
		System.out.println("Employee Information");
		System.out.println("-------------------------");
		
		// iterating the documents
		while(cursor.hasNext()) {
			
			Document document = cursor.next();
			
			System.out.println("ID : "+document.get("_id"));
			System.out.println("Name : "+document.get("name"));
			System.out.println("Designation : "+document.get("designation"));
		}

		// closing the client
		client.close();

	}
}

Output

Employee Information
————————-
ID : 102
Name : Dinesh
Designation : Sr. Software Engineer

References

1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – MongoDatabase Interface
4. JavaDoc – Document Class