Showing posts with label MongoDb-Java. Show all posts
Showing posts with label MongoDb-Java. Show all posts

Thursday, 27 July 2017

search on specific field in mongodb/Mongodb-java

mongoDB : Java : Find documents where field is equal to value

Below snippet gets all documents where “firstName” is “Gopi”.

BasicDBObject query = new BasicDBObject();
query.put("firstName", "Gopi");
             
DBCursor cursor = collection.find(query);

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 Query object */
BasicDBObject query = new BasicDBObject();
query.put("firstName", "Gopi");

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

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

}


Output

{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu"}

MongoDB-Java : Java : Get specific fields from the document from Java/MongoDb

MongoDB-Java : Java : Get specific fields from the document from Java/MongoDb

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"}

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"}

get a document from mongodb using java

mongoDB : Java : Get one document


“findOne()” method of DBCollection class returns a single object from this collection.

Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

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

Step 3 : Get collection
DBCollection collection = db.getCollection("employee");
Step 4 : Get one document using findOne() method.
DBObject doc = collection.findOne();

Step 5 : Close client
mongoClient.close();

Sample data

> db.employee.find()

{ "_id" : 1, "firstName" : "Hari Krishna", "lastName" : "Gurram", "salary" : 12345, "hobbies" : [ "writing blogs", "playing cricket", "watching movies", "reading books" ], "address" : { "office" : { "
street" : "Koramangala BDA Complex", "city" : "Bangalore", "state" : "Karnataka", "country" : "India", "PIN" : "560034" }, "home" : { "street" : "Near panchayat office", "city" : "Ongole", "state" : "
Andhra Pradesh", "country" : "India", "PIN" : "523169" } } }
{ "_id" : 2, "firstName" : "Rama Krishna", "lastName" : "Gurram", "salary" : 54321, "hobbies" : [ "playing cricket", "reading books", "travelling" ], "address" : { "office" : { "street" : "Rupena Agra
hara", "city" : "Bangalore", "state" : "Karnataka", "country" : "India", "PIN" : "560068" }, "home" : { "street" : "Near panchayat office", "city" : "Ongole", "state" : "Andhra Pradesh", "country" : "
India", "PIN" : "523169" } } }
{ "_id" : 3, "firstName" : "Jigar", "lastName" : "Shah", "salary" : 52456, "hobbies" : [ "travelling", "watching movies" ], "address" : { "office" : { "street" : "TNagar", "city" : "Chennai", "state"
: "Tamilnadu", "country" : "India", "PIN" : "341234" }, "home" : { "street" : "Ganghi Nagar", "city" : "Delhi", "state" : "Delhi", "country" : "India", "PIN" : "110037" } } }
{ "_id" : 4, "firstName" : "Piyush", "lastName" : "Rai", "salary" : 65432, "hobbies" : [ "travelling", "reading philosophy", "climbing hills" ], "address" : { "office" : { "street" : "Ameerpet", "city
" : "Hyderabad", "state" : "Andhra Pradesh", "country" : "India", "PIN" : "564321" }, "home" : { "street" : "BDA street", "city" : "Patna", "state" : "Bihar", "country" : "India", "PIN" : "324123" } }
 }
{ "_id" : 5, "firstName" : "Keerthi", "lastName" : "Parush", "salary" : 49000, "hobbies" : [ "shopping", "trecking" ], "address" : { "office" : { "street" : "Domlur", "city" : "Bangalore", "state" : "
Karnataka", "country" : "India", "PIN" : "564921" }, "home" : { "street" : "BTM Layout", "city" : "Bangalore", "state" : "Karnataka", "country" : "India", "PIN" : "234135" } } }

<pre>
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

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

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

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

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

/* Step 4: Get one document */
DBObject doc = collection.findOne();
System.out.println(doc);
/* Close client */
mongoClient.close();
}
}
</pre>

Output
{ "_id" : 1.0 , "firstName" : "Hari Krishna" , "lastName" : "Gurram" , "salary" : 12345.0 , "hobbies" : [ "writing blogs" , "playing cricket" , "watching movies" , "reading books"] , "address" : { "office" : { "street" : "Koramangala BDA Complex" , "city" : "Bangalore" , "state" : "Karnataka" , "country" : "India" , "PIN" : "560034"} , "home" : { "street" : "Near panchayat office" , "city" : "Ongole" , "state" : "Andhra Pradesh" , "country" : "India" , "PIN" : "523169"}}}

Insert a document in Mongodb using java

mongoDB : java : Insert a document


Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

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

Step 3 : Get collection
DBCollection collection = db.getCollection("employee");
Step 4 : Create a document
BasicDBObject doc = new BasicDBObject("_id", "1").append("firstName", "rajdeo").append("lastName", "singh");

Step 5 : Insert document
collection.insert(doc);


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

public class InsertDocument {

 /* 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 a document */
  BasicDBObject doc = new BasicDBObject("_id", "1").append("firstName", "rajdeo").append("lastName", "singh");
  
  /* Step 5 : Insert document */
  collection.insert(doc);
  
  System.out.println("Document inserted");
 }
}

MongoDb java client, Create a collection in MongoDb using java

mongoDB : java : Create a collection

Creating a collection is a three step process.

Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

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

Step 3: Use the create collection method, to create collection.
DBCollection collection = db.createCollection("employee", null);

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


public class DatabaseConnect {

/* 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");

DBCollection collection = db.createCollection("employee", null);

System.out.println("Collection created ");
System.out.println("Collection employee belongs to db " + collection.getDB());
}
}


Output
Collection created
Collection employee belongs to db sample