Java MongoDB Query, Find Document from Collection with Where clause - Java @ Desk

Wednesday, June 18, 2014

Java MongoDB Query, Find Document from Collection with Where clause

Java MongoDB Query, Find Document from Collection with Where clause

In our last post, we learned how to find all the documents within a collection using find() method. This post will illustrate on how to find document from a collection using a where clause to satisfy particular condition.

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

To find a document with a matching condition, we need to pass an object of BasicDBObject class with the condition. For example, we need to find out all the documents from collection Loans where name = "Personal Loan".

Refer below example to do so

import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
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 a record where Name = Personal Loan
  BasicDBObject whereQuery = new BasicDBObject();
  whereQuery.put("name", "Personal Loan");
  DBCursor cursor = collection.find(whereQuery);
  while(cursor.hasNext()) {
      System.out.println(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