Thursday, 5 March 2015

mongoDB : javaAPI : and operator example


BasicDBObject query = new BasicDBObject();
               
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("lastName", "Bandaru"));
obj.add(new BasicDBObject("firstName", "Ananad"));
       
query.put("$and", obj);

Above snippet returns all documents where “firstName” is “Ananad” and “lastName” is “Bandaru”.

Let’s say I had below data in employee 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" }
{ "_id" : 5, "firstName" : "Ananad", "lastName" : "Bandaru", "designation" : "Project Manager" }

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
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 : Create Query object */
  BasicDBObject query = new BasicDBObject();
  
  List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
  obj.add(new BasicDBObject("lastName", "Bandaru"));
  obj.add(new BasicDBObject("firstName", "Ananad"));
  
  query.put("$and", obj);
  
  System.out.println(query + "\n");
  
  /* Step 5 : Get all documents */
  DBCursor cursor = collection.find(query);
  
  /* Step 6 : Print all documents */
  while(cursor.hasNext()){
   System.out.println(cursor.next());
  }
 }
 
}


Output
{ "$and" : [ { "lastName" : "Bandaru"} , { "firstName" : "Ananad"}]}

{ "_id" : 2.0 , "firstName" : "Ananad" , "lastName" : "Bandaru"}
{ "_id" : 5.0 , "firstName" : "Ananad" , "lastName" : "Bandaru" , "designation" : "Project Manager"}

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment