Java MongoDB Query, Find All Documents in a Collection - Java @ Desk

Wednesday, June 18, 2014

Java MongoDB Query, Find All Documents in a Collection



Java MongoDB Query, Find All Documents in a Collection

To find all the records from a collection in MongoDB, first Insert Records in a Collection.

In the above example, collection Loan is created with 2 parameters :

1) name/type of loan
2) Interest rate

Below example will find all the records from a collection

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


public class MongoDBFindJava {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");

  // To Find All the Records
  DBCursor cursor = collection.find();
  while(cursor.hasNext()) {
      System.out.println("Record - " + cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}






No comments:

Post a Comment