You can retrieve documents from MongoDB using either of the following methods:
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> )
The find() method is analogous to the SELECT statement, while:
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.
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 } );
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.
Download Source Code + Libs
MongoDBQueryDemo.zip
Reference
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…