Thursday, 27 July 2017

Get all Documents in mongodb using java

mongoDB : Java : Get all Documents

“find” method of collection(without any arguments) returns all the documents in given collection.

> db.employee.find()
{ "_id" : 1, "firstName" : "Joel", "lastName" : "chelli" }
{ "_id" : 2, "firstName" : "Ananad", "lastName" : "Bandaru" }
{ "_id" : 3, "firstName" : "Gopi", "lastName" : "Battu" }
{ "_id" : 4, "firstName" : "Ritwik", "lastName" : "Mohenthy" }

Let’s say I had above data in my employee collection.

import java.net.UnknownHostException;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;

public class FindDocument {

 /* Step 1 : get mongoCLient */
 public static MongoClient getMongoClient(){
  MongoClient mongoClient = null;
   try {
    mongoClient = new MongoClient( "localhost" , 27017 );
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
   return mongoClient;
 }

 public static void main(String args[]){
  MongoClient mongoClient = getMongoClient();

  /* Step 2: Connect to DB */
  DB db = mongoClient.getDB("sample");

  /*Step 3 : Get collection */
  DBCollection collection = db.getCollection("employee");

  /* Step 4 : Get all documents */
  DBCursor cursor = collection.find();

  /* Step 5 : Get all documents */
  while(cursor.hasNext()){
   System.out.println(cursor.next());
  }
 }

}


Output

{ "_id" : 1.0 , "firstName" : "Joel" , "lastName" : "chelli"}
{ "_id" : 2.0 , "firstName" : "Ananad" , "lastName" : "Bandaru"}
{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu"}
{ "_id" : 4.0 , "firstName" : "Ritwik" , "lastName" : "Mohenthy"}

No comments:

Post a Comment