Thursday 5 March 2015

mongoDB : Java : Get specific fields from the document


usually “find()” method returns all the fields of document. You can restrict the fields returned be find query by passing “keys” document as a parameter.

Example
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
fields.put("firstName", 1);
fields.put("lastName", 1);
fields.put("_id", 0);
               
DBCursor cursor = collection.find(query, fields);

Above snippet returns "firstName" and "lastName" fields of the documents. Result documents will not contain "_id" field.

> 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.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 keys to get in result */
  BasicDBObject query = new BasicDBObject();
  BasicDBObject fields = new BasicDBObject();
  fields.put("firstName", 1);
  fields.put("lastName", 1);
  fields.put("_id", 0);
  
  /* Step 5 : Get all documents */
  DBCursor cursor = collection.find(query, fields);
  
  /* Step 6 : Print all documents */
  while(cursor.hasNext()){
   System.out.println(cursor.next());
  }
 }
 
}


Output
{ "firstName" : "Joel" , "lastName" : "chelli"}
{ "firstName" : "Ananad" , "lastName" : "Bandaru"}
{ "firstName" : "Gopi" , "lastName" : "Battu"}
{ "firstName" : "Ritwik" , "lastName" : "Mohenthy"}

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment