Categories: MongoDB

Java MongoDB Query a Document to Database

In this tutorial one Of the four basic database operations (i.e. CRUD), read operation are those that retrieve records or documents from a collection in MongoDB. For general information about read operations and the factors that affect their performance, see Read Operations; for documentation of the other CRUD operations.

You can retrieve documents from MongoDB using either of the following methods:

  • find
  • findOne

Find

The find() method is the primary method to select documents from a collection. The find() method returns a cursor that contains a number of documents. Most drivers provide application developers with a native iterable interface for handling cursors and accessing documents. The find() method has the following syntax:

db.collection.find( <query>, <projection> ) 
 
Corresponding Operation in SQL

The find() method is analogous to the SELECT statement, while:

  • the <query> argument corresponds to the WHERE statement, and
  • the <projection> argument corresponds to the list of fields to select from the result set.

Find One

The findOne() method selects and returns a single document from a collection and returns that document. findOne() does not return a cursor.

The findOne() method has the following syntax:

db.collection.findOne( <query>, <projection> ) 
 

Except for the return value, findOne() method is quite similar to the find() method; in fact, internally, the findOne() method is the find() method with a limit of 1.

Cursor

The find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable, then the cursor is automatically iterated up to 20 times  to print up to the first 20 documents that match the query, as in the following example:

db.bios.find( { _id: 1 } );
 Click here to know more about the Read Data and its options.

In Java MongoDB API, you can use collection.find() to get / query document from collection. Here is few common use cases :

For this example we have insert some document into the mongoDB “dineshonjavaDB
as follows inserting 10 documents to the “employee” collection on mongoDB.

for (int i=10001; i <= 10010; i++) {
 collection.insert(new BasicDBObject().append("empId", i));
}

1. Fetch first record.

DBObject doc = collection.findOne(); //get first document
System.out.println(dbObject);

2. Get the set of document.

DBCursor cursor = collection.find();
while(cursor.hasNext()) {
    System.out.println(cursor.next());
}

3. fetch documents where empId = 8.

BasicDBObject query = new BasicDBObject();
query.put("empId", 10008);
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
    System.out.println(cursor.next());
}

4. fetch documents where number = 10009 and 10010, use “$in” operator.

BasicDBObject query = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(10009);
list.add(10010);
query.put("empId", new BasicDBObject("$in", list));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
   System.out.println(cursor.next());
}

5. fetch documents where empId > 10003, use “$gt” operator.

BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$gt", 10003));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
 System.out.println(cursor.next());
}

6. fetch documents where 10002 < number < 10005, combine two operators, “$gt” and “$lt”.

BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$gt", 10002).append("$lt", 10005));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
 System.out.println(cursor.next());
}

7. fetch documents where number != 10001, use “$ne” operator.

BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$ne", 10001));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
  System.out.println(cursor.next());
}

Now lets see the full example and run this ..

package com.dineshonjava.mongo.test;

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

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * @author Dinesh Rajput
 *
 */
public class ReadDocumentDemo {

 public static void main(String[] args) {
 
 try {
 
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("dineshonjavaDB");
 
  // get a single collection
  DBCollection collection = db.getCollection("employeesCollection");

  // insert empId 10001 to 10010 for testing
  for (int i = 10001; i <= 10010; i++) {
   collection.insert(new BasicDBObject().append("empId", i));
  }

  // get first document
  DBObject dbObject = collection.findOne();
  System.out.println(dbObject);
  System.out.println("*****************First Test*****************");
  // get all available documents
  DBCursor cursor = collection.find();
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
  System.out.println("*****************Second Test*****************");
  // get document, where empId = 10003
  BasicDBObject query = new BasicDBObject();
  query.put("empId", 10003);
  DBCursor cursor2 = collection.find(query);
  while (cursor2.hasNext()) {
   System.out.println(cursor2.next());
  }
  System.out.println("*****************Third Test*****************");
  // get document, where empId = 10002 and empId = 10004
  BasicDBObject query2 = new BasicDBObject();
  List<Integer> list = new ArrayList<Integer>();
  list.add(10002);
  list.add(10004);
  query2.put("empId", new BasicDBObject("$in", list));
  DBCursor cursor3 = collection.find(query2);
  while (cursor3.hasNext()) {
   System.out.println(cursor3.next());
  }
  System.out.println("*****************Fourth Test*****************");
  // get document, where empId > 10006
  BasicDBObject query3 = new BasicDBObject();
  query3.put("empId", new BasicDBObject("$gt", 10006));
  DBCursor cursor4 = collection.find(query3);
  while (cursor4.hasNext()) {
   System.out.println(cursor4.next());
  }
  System.out.println("*****************Fifth Test*****************");
  // get document, where 10005 < empId < 10007
  BasicDBObject query4 = new BasicDBObject();
  query4.put("empId", new BasicDBObject("$gt", 10005).append("$lt", 10007));
  DBCursor cursor5 = collection.find(query4);
  while (cursor5.hasNext()) {
   System.out.println(cursor5.next());
  }
  System.out.println("*****************Sixth Test*****************");
  // get document, where empId != 10008
  BasicDBObject query5 = new BasicDBObject();
  query5.put("empId", new BasicDBObject("$ne", 10008));
  DBCursor cursor6 = collection.find(query5);
  while (cursor6.hasNext()) {
   System.out.println(cursor6.next());
  }

  System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}

If every thing is fine then run as Java Application we will get the following output on the console.

output: 
{ “_id” : { “$oid” : “5106c015c781b5829079a5da”} , “empId” : 10001}
 *****************First Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5da”} , “empId” : 10001}
 { “_id” : { “$oid” : “5106c015c781b5829079a5db”} , “empId” : 10002}
 { “_id” : { “$oid” : “5106c015c781b5829079a5dc”} , “empId” : 10003}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dd”} , “empId” : 10004}
 { “_id” : { “$oid” : “5106c015c781b5829079a5de”} , “empId” : 10005}
 { “_id” : { “$oid” : “5106c015c781b5829079a5df”} , “empId” : 10006}
 { “_id” : { “$oid” : “5106c015c781b5829079a5e0”} , “empId” : 10007}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e1”} , “empId” : 10008}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e2”} , “empId” : 10009}
 { “_id” : { “$oid” : “5106c015c781b5829079a5e3”} , “empId” : 10010}
 *****************Second Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5dc”} , “empId” : 10003}
*****************Third Test*****************
 { “_id” : { “$oid” : “5106c015c781b5829079a5db”} , “empId” : 10002}
 { “_id” : { “$oid” : “5106c015c781b5829079a5dd”} , “empId” : 10004}
 *****************Fourth Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5e0”} , “empId” : 10007}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e1”} , “empId” : 10008}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e2”} , “empId” : 10009}
 { “_id” : { “$oid” : “5106c015c781b5829079a5e3”} , “empId” : 10010}
*****************Fifth Test*****************
 { “_id” : { “$oid” : “5106c015c781b5829079a5df”} , “empId” : 10006}
 *****************Sixth Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5da”} , “empId” : 10001}
 { “_id” : { “$oid” : “5106c015c781b5829079a5db”} , “empId” : 10002}
 { “_id” : { “$oid” : “5106c015c781b5829079a5dc”} , “empId” : 10003}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dd”} , “empId” : 10004}
{ “_id” : { “$oid” : “5106c015c781b5829079a5de”} , “empId” : 10005}
{ “_id” : { “$oid” : “5106c015c781b5829079a5df”} , “empId” : 10006}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e0”} , “empId” : 10007}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e2”} , “empId” : 10009}
 { “_id” : { “$oid” : “5106c015c781b5829079a5e3”} , “empId” : 10010}
Done

Download Source Code + Libs
MongoDBQueryDemo.zip

Reference

MongoDB operator documentation

                             <<previous<<             || index  ||         >>next>>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago