FIND/SEARCH/Query/Display/Select from Collection In MongoDb in java



In this mongoDB tutorial we will write java programs to FIND/SEARCH/Query/Display/Select from Collection In MongoDb in java in different possible manners.

Contents of page >
1) Program to Query all Document From Collection In MongoDb in java >
package queryDocumentFromCollectionInMongoDb;
/**
* Write a program to Query all Document From Collection In MongoDb in java
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class QueryDocumentFromCollectionInMongoDb1 {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document/record in COLLECTION in MongoDB */
          System.out.println("Insert document 1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Sam");
         
          /* Insert document/record in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /**\nDisplay all DOCUMENTS of COLLECTION in MongoDB */
          System.out.println("\nDisplay all DOCUMENTS of COLLECTION in MongoDB ");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
                      
   }
}
/* OUTPUT
Insert document 1
Insert document2
Display all DOCUMENTS of COLLECTION in MongoDB
{ "_id" : { "$oid" : "585c17557dbba63f2481eec7"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "585c17557dbba63f2481eec8"} , "id" : 2 , "name" : "Sam"}
*/

Download >
Now, it’s time to Download maven Project :) Click here.

Read : How to Import Maven project in eclipse

OR


2) Program to Query Document From Collection In MongoDb in java on Basis Of Multiple Conditions >

package queryDocumentFromCollectionInMongoDb;
/**
* Write a program to Query Document From Collection In MongoDb in java on Basis Of Multiple Conditions
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class QueryDocumentFromCollectionInMongoDb2_onBasisOfMultipleConditions {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
          /* create a BasicDBObject1 (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
          basicDBObject1.put("salary", 100);
         
          /* Insert document1/record1 in collection in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject2 (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Ankit");
          basicDBObject2.put("salary", 200);
         
          /* Insert document2/record2 in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* Display collection before QUERING collection in MongoDB */
          System.out.println("\nDisplay collection before QUERING collection in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage dbCollection looks like this >
          { "_id" : { "$oid" : "58558a94ad8dc837cc7d94ae"} , "id" : 1 , "name" : "Ankit" , "salary" : 100}
          { "_id" : { "$oid" : "58558a94ad8dc837cc7d94af"} , "id" : 2 , "name" : "Ankit" , "salary" : 200}
          */
         
         
          /** Now, let's QUERY the document */
         
          /** FIND document where
          * id = 1 and
          * name = "Ankit"
          */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.append("id", 1).append("name", "Ankit");
          /** Execute FIND/SEARCH query - To FIND DOCUMENT in MongoDB */
          //find method Select documents in collection and returns cursor to the selected documents.
          System.out.println("\nExecute FIND/SEARCH query - "
                       + "To FIND DOCUMENT where id = 1 and name = 'Ankit'");
          DBCursor cursor = dbCollection.find(basicDBObject_SearchCondition);
         
          /* Display documents of collection after QUERING collection in MongoDB */
          System.out.println("\nDisplay documents of collection after QUERING collection in MongoDB ");
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
          /** At this stage dbCollection looks like this >
          { "_id" : { "$oid" : "58558a94ad8dc837cc7d94ae"} , "id" : 1 , "name" : "Ankit" , "salary" : 100}
          */
         
   }
}
/* OUTPUT
Insert document1
Insert document2
Display collection before QUERING collection in MongoDB
{ "_id" : { "$oid" : "58558a94ad8dc837cc7d94ae"} , "id" : 1 , "name" : "Ankit" , "salary" : 100}
{ "_id" : { "$oid" : "58558a94ad8dc837cc7d94af"} , "id" : 2 , "name" : "Ankit" , "salary" : 200}
Execute FIND/SEARCH query - To FIND DOCUMENT where id = 1 and name = 'Ankit'
Display documents of collection after QUERING collection in MongoDB
{ "_id" : { "$oid" : "58558a94ad8dc837cc7d94ae"} , "id" : 1 , "name" : "Ankit" , "salary" : 100}
*/

3) Program to Query Document From Collection In MongoDb in java using $in Operator>

Read : Find documents using $in operator In MongoDb in java


4) Program to Query Document From Collection In MongoDb in java using gt and gte Operators >
4.1) Program to Query Document From Collection In MongoDb in java using gt (greater than) Operator >
package queryDocumentFromCollectionInMongoDb;
/**
* Write a program to Query Document From Collection In MongoDb in java using Gt Operator
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class QueryDocumentFromCollectionInMongoDb4_usingGtAndGteOperator {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject1 (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document1/record1 in COLLECTION in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject2 (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Sam");
         
          /* Insert document2 in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* create a BasicDBObject3 (document /record) */
          BasicDBObject basicDBObject3 = new BasicDBObject();
          basicDBObject3.put("id", 3);
          basicDBObject3.put("name", "Neh");
         
          /* Insert document3 in collection in MongoDB */
          System.out.println("Insert document3");
          dbCollection.insert(basicDBObject3);        
          /* Display documents of collection before QUERING DOCUMENTs in MongoDB */
          System.out.println("\nDisplay collection "
                       + "before QUERING collection in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage dbCollection looks like this >
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
          */
         
         
          /** Now, let's FIND the documents from collection in MongoDB */
          /** FIND documents where id > 2 */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
                                               //$gt operator is for GREATER THAN
                                               //Pass > $gt as key > and > 2 as value
          basicDBObject_SearchCondition.put("id",
                       new BasicDBObject("$gt", 2));
          /** Execute FIND/SEARCH query - To FIND DOCUMENT in MongoDB */
          //find method Select documents in collection and returns cursor to the selected documents.
          System.out.println("\nExecute FIND query where id > 2");
          DBCursor cursor = dbCollection.find(basicDBObject_SearchCondition);
         
          /* Display documents of collection after QUERING collection in MongoDB */
          System.out.println("\nDisplay documents of collection "
                       + "after QUERING collection in MongoDB ");
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
          /** At this stage dbCollection looks like this >
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
          */
         
   }
}
/* OUTPUT
Insert document1
Insert document2
Insert document3
Display collection before QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
Execute FIND query where id > 2
Display documents of collection after QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
*/

4.2) Program to Query Document From Collection In MongoDb in java using gte (greater than equal) Operator >
FIND documents where id >= 2 From this collection >
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
                                      //$gte operator is for GREATER THAN EQUAL
                                      //Pass > $gte as key - and - 2 as value
basicDBObject_SearchCondition.put("id", new BasicDBObject("$gte", 2));
Result >
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}

5) Program to Query Document From Collection In MongoDb in java using lt and lte Operators >
5.1) Program to Query Document From Collection In MongoDb in java using lt (less than) Operator >
5.2) Program to Query Document From Collection In MongoDb in java using lte (less than equal) Operator >

Please read : Find documents where field is (less than) using lt and lte operator In MongoDb in java


6) Program to Query Document From Collection In MongoDb in java using eq and ne Operator >
6.1) Program to Query Document From Collection In MongoDb in java using eq (equals) Operator >
package queryDocumentFromCollectionInMongoDb;
/**
* Write a program to Query Document From Collection In MongoDb in java using Eq And Ne Operator
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class QueryDocumentFromCollectionInMongoDb6_usingEqAndNeOperator {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject1 (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document1/record1 in COLLECTION in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject2 (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Sam");
         
          /* Insert document2 in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* create a BasicDBObject3 (document /record) */
          BasicDBObject basicDBObject3 = new BasicDBObject();
          basicDBObject3.put("id", 3);
          basicDBObject3.put("name", "Neh");
         
          /* Insert document3 in collection in MongoDB */
          System.out.println("Insert document3");
          dbCollection.insert(basicDBObject3);        
          /* Display documents of collection before QUERING DOCUMENTs in MongoDB */
          System.out.println("\nDisplay collection "
                       + "before QUERING collection in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage dbCollection looks like this >
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
          */
         
         
          /** Now, let's FIND the documents from collection in MongoDB */
          /** FIND documents where id = 2 */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
                                            //$eq operator is for EQUALS TO
                                            //Pass > $eq as key > and > 2 as value
          basicDBObject_SearchCondition.put("id",
                       new BasicDBObject("$eq", 2));
          /** Execute FIND/SEARCH query - To FIND DOCUMENT in MongoDB */
          //find method Select documents in collection and returns cursor to the selected documents.
          System.out.println("\nExecute FIND query where id = 2 ");
          DBCursor cursor = dbCollection.find(basicDBObject_SearchCondition);
         
          /* Display documents of collection after QUERING collection in MongoDB */
          System.out.println("\nDisplay documents of collection "
                       + "after QUERING collection in MongoDB ");
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
          /** At this stage dbCollection looks like this >
          { "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
          */
         
   }
}
/* OUTPUT
Insert document1
Insert document2
Insert document3
Display collection before QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
Execute FIND query where id = 2
Display documents of collection after QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
*/

6.2) Program to Query Document From Collection In MongoDb in java using ne (not equals) Operator >

FIND documents where id != 2 From this collection
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
                                                  //$ne operator is for NOT EQUALS TO
                                                  //Pass > $ne as key - and - 2 as value
basicDBObject_SearchCondition.put("id", new BasicDBObject("$ne", 2));
Result
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}

7) Program to Query Document from Collection In MongoDb in java using Gt and Lt Operator >
/**
* Write a program to Query Document from Collection In MongoDb in java using Gt And Lt Operator
*/
package queryDocumentFromCollectionInMongoDb;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class QueryDocumentFromCollectionInMongoDb7_usingGtAndLtOperator {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject1 (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document1/record1 in COLLECTION in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject2 (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Sam");
         
          /* Insert document2 in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* create a BasicDBObject3 (document /record) */
          BasicDBObject basicDBObject3 = new BasicDBObject();
          basicDBObject3.put("id", 3);
          basicDBObject3.put("name", "Neh");
         
          /* Insert document3 in collection in MongoDB */
          System.out.println("Insert document3");
          dbCollection.insert(basicDBObject3);        
          /* Display documents of collection before QUERING DOCUMENTs in MongoDB */
          System.out.println("\nDisplay collection before QUERING collection in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage dbCollection looks like this >
                { "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
                { "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
                { "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
          */
         
         
          /** Now, let's FIND the documents from collection in MongoDB */
          /** FIND documents where id > 1 and id < 3 */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.put("id", new BasicDBObject()
                                                 .append("$gt", 1)                                                                                          
                                                .append("$lt", 3)
                                        );
          /** Execute FIND/SEARCH query - To FIND DOCUMENT in MongoDB */
          //find method Select documents in collection and returns cursor to the selected documents.
          System.out.println("\nExecute FIND query where id > 1 and id < 3 ");
          DBCursor cursor = dbCollection.find(basicDBObject_SearchCondition);
         
          /* Display documents of collection after QUERING collection in MongoDB */
          System.out.println("\nDisplay documents of collection "
                       + "after QUERING collection in MongoDB ");
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
          /** At this stage dbCollection looks like this >
               { "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
          */
         
   }
}
/* OUTPUT
Insert document1
Insert document2
Insert document3
Display collection before QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
Execute FIND query where id > 1 and id < 3
Display documents of collection after QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Sam"}
*/
Here we used combination of $gt, $lt.
Likewise you may try combination of $gte, $lte etc..

8) Program to Query Document From Collection In MongoDb in java using And Operator >
package queryDocumentFromCollectionInMongoDb;
/**
* Write a program to Query Document From Collection In MongoDb in java using And Operator
*/
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
public class QueryDocumentFromCollectionInMongoDb8_usingAndOperator {
   public static void main(String[] args) {
          /* Connect to MongoDB */
          MongoClient mongoClient =
                       new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
         
          /* Connect to DATABASE */
          //If in case database doesn't exists, it will be created at runtime
          DB db = mongoClient.getDB("mydb");
                      
          /* Get the COLLECTION (TABLE) */
          //If in case collection (Table) doesn't exists, it will be created at runtime
          DBCollection dbCollection = db.getCollection("Employee");
          /*If collection already exists, you may remove everything
          from collection for perfect OUTPUT of program*/
          dbCollection.remove(new BasicDBObject()); //Not Mandatory
                      
         
          /* create a BasicDBObject1 (document /record) */
          BasicDBObject basicDBObject1 = new BasicDBObject();
          basicDBObject1.put("id", 1);
          basicDBObject1.put("name", "Ankit");
         
          /* Insert document1/record1 in COLLECTION in MongoDB */
          System.out.println("Insert document1");
          dbCollection.insert(basicDBObject1);
         
          /* create a BasicDBObject2 (document /record) */
          BasicDBObject basicDBObject2 = new BasicDBObject();
          basicDBObject2.put("id", 2);
          basicDBObject2.put("name", "Ankit");
         
          /* Insert document2 in collection in MongoDB */
          System.out.println("Insert document2");
          dbCollection.insert(basicDBObject2);        
          /* create a BasicDBObject3 (document /record) */
          BasicDBObject basicDBObject3 = new BasicDBObject();
          basicDBObject3.put("id", 3);
          basicDBObject3.put("name", "Neh");
         
          /* Insert document3 in collection in MongoDB */
          System.out.println("Insert document3");
          dbCollection.insert(basicDBObject3);        
          /* Display documents of collection before QUERING DOCUMENTs in MongoDB */
          System.out.println("\nDisplay collection before QUERING collection in MongoDB");
          DBCursor cursor0 = dbCollection.find();
          while (cursor0.hasNext()) {
                 System.out.println(cursor0.next());
          }
         
          /** At this stage dbCollection looks like this >
               { "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
               { "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Ankit"}
               { "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
          */
         
         
          /** Now, let's FIND the documents from collection in MongoDB */
          /** FIND documents where
          id = 1 AND name = "Ankit" */
          BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
          basicDBObject_SearchCondition.put("$and", new BasicDBObject[]{
                                               new BasicDBObject("id", 1),
                                               new BasicDBObject("name", "Ankit")
                                                                         }                                                                   
                                             );
          /** Execute FIND/SEARCH query - To FIND DOCUMENT in MongoDB */
          //find method Select documents in collection and returns cursor to the selected documents.
          System.out.println("\nExecute FIND query where id = 1 AND name = 'Ankit' ");
          DBCursor cursor = dbCollection.find(basicDBObject_SearchCondition);
         
          /* Display documents of collection after QUERING collection in MongoDB */
          System.out.println("\nDisplay documents of collection "
                       + "after QUERING collection in MongoDB ");
          while (cursor.hasNext()) {
                 System.out.println(cursor.next());
          }
          /** At this stage dbCollection looks like this >
                 { "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
          */
         
   }
}
/* OUTPUT
Insert document1
Insert document2
Insert document3
Display collection before QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
Execute FIND query where id = 1 AND name = 'Ankit'
Display documents of collection after QUERING collection in MongoDB
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
*/
/*
FIND documents where id = 1 OR name = "Ankit" From this collection
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a40"} , "id" : 3 , "name" : "Neh"}
BasicDBObject basicDBObject_SearchCondition = new BasicDBObject();
basicDBObject_SearchCondition.put("$or", new BasicDBObject[]{
                                       new BasicDBObject("id", 1),
                                       new BasicDBObject("name", "Ankit")
                                                                       }                                                                   
                                                   );
Result
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3e"} , "id" : 1 , "name" : "Ankit"}
{ "_id" : { "$oid" : "58559179ad8dc831e8df7a3f"} , "id" : 2 , "name" : "Ankit"}
*/

9) Program to Query single Document From Collection In MongoDb in java >
/** findOne method returns a single document from collection. */
DBObject dbObject = dbCollection.findOne();
So, we inserted two records but only one record was fetched using findOne method.


Download >
Now, it’s time to Download maven Project :) Click here.

Read : How to Import Maven project in eclipse

OR


Summary -
So in this MongoDB tutorial we learned with example and program how to FIND/SEARCH/Query/Display/Select from Collection In MongoDb in java in different possible manners.

Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com(JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.

RELATED LINKS>







eEdit
Must read for you :