MongoDB Get all Documents using Java Example

MongoDB Get all Documents using Java

In this example, We will show you simple program about, How to perform MongoDB get all documents using Java. The example program has been tested with mongodb server 3.4.2 environment and output were shared in the same post.

Available Records

Mongodb Get all Documents using 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 GetDocuments {

	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");
		
		// getting the all documents from collection
		FindIterable<Document> documents = collection.find();
		
		// preparing for an iteration
		MongoCursor<Document> cursor = documents.iterator();
		
		System.out.printf("%-10s %-10s %-15s %n", "ID", "Name", "Designation");
		
		System.out.println("----------------------------------------------");
		
		// iterating the documents
		while(cursor.hasNext()) {
			
			Document document = cursor.next();
			
			System.out.printf("%-10s %-10s %-15s %n", document.get("_id"), document.get("name"), document.get("designation"));
		}
		
		// closing the connection
		client.close();
		
	}
}

Output

ID Name Designation
———————————————-
101 John Software Engineer
102 Dinesh Sr. Software Engineer
103 Smith Project Manager
104 William Software Engineer
105 James Business Analyst

References

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