MongoDB Java using Find and Query Operations Example Tutorial

MongoDB Java using Find and Query Operations Example Tutorial

In this tutorial, MongoDB Java using Find and Query Operations Example Tutorial we will focus on using Find and Query Operations to retrieve data from a MongoDB collection. We will concentrate on using the following MongoDB operators: ($gt, $lt, $gte, $lte, $in, $nin, $and and $or) with the latest version of MongoDB using Java and MongoDB Java Driver (mongo-java-driver-3.2.0.jar).

In our previous tutorial “MongoDB Java CRUD Operations Example Tutorial“, we covered how to perform CRUD Operations (Create, Read, Update and Delete) with the latest version of MongoDB. Since this data is already residing on our MongoDB ‘inventory’ collection we are ready to continue with minimum setup, so let’s dive right in.

What’s Covered

  1. Connecting to MongoDB Server using MongoClient
  2. Show All documents in MongoDB Example
  3. Show All documents with Price Greater than Example
  4. Show All documents with Price Less than Example
  5. Show All documents with Quantity Greater than or Equal To Example
  6. Show All documents within a given Price Range Example
  7. Show All documents with Sub-Category Not Equal To Example
  8. Show All documents with Item Id IN clause Example
  9. Show All documents with Item Id NOT IN clause Example
  10. Show All documents using AND clause Example
  11. Show All documents using OR clause Example

Getting Started

In order to run this tutorial yourself, you will need the following:

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
mongo-java-driver-3.2.0.jar

Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

mongodb_query_proj_struct

Connecting to MongoDB Server using MongoClient

MongoClient is used to make a connection to MongoDB server. In our example, we use MongoClient to get a database object and connect to the ‘test’ database where we make use of the ‘inventory’ collection.

MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("inventory");

Query for All Documents in a Collection in MongoDB

In this example, we begin by showing you how to return all documents in a collection. In order to do this, we call the find() method without a criteria document. For example, the following operation queries for all documents in the ‘inventory’ collection.

private static void showAllDocuments(
		final MongoCollection<Document> collection) {

	System.out.println("----[ Show All Items ]----");
	for (Document doc : collection.find()) {
		System.out.println(doc.toJson());
	}
}
----[ Show All Items ]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. 
Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" 
: "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 29.74, "list-price" 
: 39.99, "quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. 
Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. 
Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" 
: "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, 
"quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & 
Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, 
"quantity" : 65 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", 
"category" : "Coffee Machines", "sub-category" : "Programmable Coffee 
Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi 
DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : 
"DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" 
: 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" 
: 36.95, "quantity" : 26 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart 
DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed 
Chrome/Black", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" 
: "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 305.0, 
"list-price" : 159.99, "quantity" : 6 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. 
Coffee BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless 
Steel", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : 
"Coffee Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, 
"list-price" : 89.99, "quantity" : 3 }
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro 
French Coffee Press", "manufacturer" : null, "dept" : null, "category" : 
"Coffee Machines", "sub-category" : "French Press", "price" : 31.99, 
"list-price" : 72.99, "quantity" : 12 }

Show All documents using Greater Than Operator

In this example, we query for all documents using the $gt where Price is Greater Than a certain price.

private static void findPriceGreaterThanQuery(
		final MongoCollection<Document> collection, final double price) {

	BasicDBObject query = new BasicDBObject();
	query.put("price", new BasicDBObject("$gt", price));

	System.out.println(String.format(
			"----[ List All Items Price Greater than %1$,.2f ]----", price));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items Price Greater than 95.00 ]----
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", 
"category" : "Coffee Machines", "sub-category" : "Programmable Coffee 
Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" 
: 36.95, "quantity" : 26 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart 
DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed 
Chrome/Black", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" 
: "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 305.0, 
"list-price" : 159.99, "quantity" : 6 }

Show All documents using Less Than Operator

In this example, we query for all documents using the $lt where Price is Less Than a certain price.

private static void findPriceLessThanQuery(
		final MongoCollection<Document> collection, final double price) {

	BasicDBObject query = new BasicDBObject();
	query.put("price", new BasicDBObject("$lt", price));

	System.out.println(String.format(
			"----[ List All Items Price Less than %1$,.2f ]----", price));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items Price Less than 100.00 ]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. 
Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" 
: "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 29.74, "list-price" 
: 39.99, "quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. 
Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. 
Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" 
: "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, 
"quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & 
Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, 
"quantity" : 65 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi 
DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : 
"DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" 
: 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" 
: 36.95, "quantity" : 26 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. 
Coffee BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless 
Steel", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : 
"Coffee Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, 
"list-price" : 89.99, "quantity" : 3 }
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro 
French Coffee Press", "manufacturer" : null, "dept" : null, "category" : 
"Coffee Machines", "sub-category" : "French Press", "price" : 31.99, 
"list-price" : 72.99, "quantity" : 12 }

Show All documents using Greater Than or Equal To Operator

In this example, we query for all documents using the $gte where Quantity is Greater Than or Equal To a certain amount.

private static void findQuantityGreaterThanEqualQuery(
		final MongoCollection<Document> collection, final int quantity) {

	BasicDBObject query = new BasicDBObject();
	query.put("quantity", new BasicDBObject("$gte", quantity));

	System.out.println(String.format(
			"----[ List All Items Quantity Greater than or Equal to %d ]----",
			quantity));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items Quantity Greater than or Equal to 21 ]----
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. 
Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. 
Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" 
: "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, 
"quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & 
Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, 
"quantity" : 65 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi 
DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : 
"DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" 
: 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" 
: 36.95, "quantity" : 26 }

Show All documents using Price is in a Certain Range

In this example, we query for all documents using the $lte where Price falls between a certain Price Range using Greater Than or Equal To and Less Than or Equal To operators.

private static void findPriceInRangeQuery(
		final MongoCollection<Document> collection, final double lowPrice,
		final double highPrice) {

	BasicDBObject query = new BasicDBObject();
	query.put("price",
			new BasicDBObject("$gte", lowPrice).append("$lte", highPrice));

	System.out.println(String.format(
			"----[ List All Items Price Greater than or Equal to %1$,.2f "
					+ "and Less Than or Equal to %2$,.2f ]----",
			lowPrice, highPrice));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items Price Greater than or Equal to 90.00 and Less Than or 
Equal to 300.00 ]----
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", 
"category" : "Coffee Machines", "sub-category" : "Programmable Coffee 
Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" 
: 36.95, "quantity" : 26 }

Show All documents with Sub-Category Not Equal To Example

In this example, we query for all documents using the $ne where Sub-Category NOT Equal To ‘Built-in Grinders’.

private static void findSubCategoryNotEqualToQuery(
		final MongoCollection<Document> collection,
		final String subCategory) {

	BasicDBObject query = new BasicDBObject();
	query.put("sub-category", new BasicDBObject("$ne", subCategory));

	System.out.println(String.format(
			"----[ List All Items whose sub-category Not Equal to '%s' ]----",
			subCategory));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items whose sub-category Not Equal to 'Built-in Grinders' ]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. 
Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" 
: "Mr. Coffee", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 29.74, "list-price" 
: 39.99, "quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. 
Coffee DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. 
Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" 
: "Programmable Coffee Makers", "price" : 24.99, "list-price" : 19.99, 
"quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & 
Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 19.99, "list-price" : 14.96, 
"quantity" : 65 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", 
"category" : "Coffee Machines", "sub-category" : "Programmable Coffee 
Makers", "price" : 185.0, "list-price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi 
DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : 
"DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 70.0, "list-price" 
: 53.99, "quantity" : 21 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", 
"sub-category" : "Programmable Coffee Makers", "price" : 99.99, "list-price" 
: 36.95, "quantity" : 26 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart 
DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed 
Chrome/Black", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" 
: "Coffee Machines", "sub-category" : "Built-in Griders", "price" : 305.0, 
"list-price" : 159.99, "quantity" : 6 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. 
Coffee BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless 
Steel", "manufacturer" : "Mr. Coffee", "dept" : "kitchen", "category" : 
"Coffee Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, 
"list-price" : 89.99, "quantity" : 3 }
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro 
French Coffee Press", "manufacturer" : null, "dept" : null, "category" : 
"Coffee Machines", "sub-category" : "French Press", "price" : 31.99, 
"list-price" : 72.99, "quantity" : 12 }

Show All documents with Item Id IN clause Example

In this example, we query for all documents using the $in where Item-ID are IN the provided list of entries.

private static void findItemIdInListQuery(
		final MongoCollection<Document> collection,
		final List<String> items) {

	BasicDBObject query = new BasicDBObject();
	query.put("item-id", new BasicDBObject("$in", items));

	System.out.println(String.format(
			"----[ List All Items whose item-id IN '%s' ]----", items));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items whose item-id IN '[B003TOAM98, B000T9SCZ2, B002IASYA8, 
B0037ZG3DS]' ]----
{ "_id" : "1454163345", "item-id" : "B003TOAM98", "description" : "DeLonghi 
DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black", "manufacturer" : 
"DeLonghi", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" 
: "Programmable Coffee Makers", "price" : 70.0, "list_price" : 53.99, 
"quantity" : 21 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart 
DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black", 
"manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee 
Machines", "sub-category" : "Built-in Griders", "price" : 305.0, "list_price" 
: 159.99, "quantity" : 6 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. Coffee 
BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless Steel", 
"manufacturer" : "Mr. Coffee", "department" : "kitchen", "category" : "Coffee 
Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, "list-price" : 
89.99, "quantity" : 3 }

Show All documents with Item Id NOT IN clause Example

In this example, we query for all documents using the $nin where Item-ID are NOT IN the provided list of entries.

private static void findItemIdNotInListQuery(
		final MongoCollection<Document> collection,
		final List<String> items) {

	BasicDBObject query = new BasicDBObject();
	query.put("item-id", new BasicDBObject("$nin", items));

	System.out.println(String.format(
			"----[ List All Items whose item-id NOT IN '%s' ]----", items));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items whose item-id NOT IN '[B003TOAM98, B000T9SCZ2, 
B002IASYA8, B0037ZG3DS]' ]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. Coffee 
BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" : "Mr. 
Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 29.74, "list_price" : 39.99, 
"quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. Coffee 
DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. Coffee", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 24.99, "list_price" : 19.99, 
"quantity" : 32 }
{ "_id" : "1454163343", "item-id" : "B001NXC5YC", "description" : "Black & 
Decker DCM600B 5-Cup Coffeemaker, Black", "manufacturer" : "Black & Decker", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 19.99, "list_price" : 14.96, 
"quantity" : 65 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" 
: "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 
185.0, "list_price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163346", "item-id" : "B001A61BMO", "description" : "Kalorik 
1000-Watt 12-Cup Programmable Coffeemaker, Copper", "manufacturer" : 
"Kalorik", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" 
: "Programmable Coffee Makers", "price" : 99.99, "list_price" : 36.95, 
"quantity" : 26 }
{ "_id" : "1454163352", "item-id" : null, "description" : "SterlingPro French 
Coffee Press", "manufacturer" : null, "department" : null, "category" : 
"Coffee Machines", "sub-category" : "French Press", "price" : 31.99, 
"list-price" : 72.99, "quantity" : 12 }

Show All documents using AND clause Example

In this example, we query for all documents using the $and where Manufacturer AND Dept meet the given criteria.

private static void findItemLogicalAndQuery(
		final MongoCollection<Document> collection,
		final String manufacturer, final String department) {

	BasicDBObject query = new BasicDBObject();
	List<BasicDBObject> andQuery = new ArrayList<BasicDBObject>();
	andQuery.add(new BasicDBObject("manufacturer", manufacturer));
	andQuery.add(new BasicDBObject("dept", department));
	query.put("$and", andQuery);

	System.out.println(String.format(
			"----[ List All Items with manufacturer=%s AND department=%s ]----",
			manufacturer, department));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items with manufacturer=Cuisinart AND department=kitchen ]----
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" 
: "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 
185.0, "list_price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart 
DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black", 
"manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee 
Machines", "sub-category" : "Built-in Griders", "price" : 305.0, "list_price" 
: 159.99, "quantity" : 6 }

Show All documents using OR clause Example

In this example, we query for all documents using the $or where Manufacturer OR Manufacturer to meet the given criteria.

private static void findItemLogicalOrQuery(
		final MongoCollection<Document> collection,
		final String manufacturer, final String manufacturer1) {

	BasicDBObject query = new BasicDBObject();
	List<BasicDBObject> orQuery = new ArrayList<BasicDBObject>();
	orQuery.add(new BasicDBObject("manufacturer", manufacturer));
	orQuery.add(new BasicDBObject("manufacturer", manufacturer1));
	query.put("$or", orQuery);

	System.out.println(String.format(
			"----[ List All Items with manufacturer=%s or manufacturer=%s ]----",
			manufacturer, manufacturer1));
	for (Document doc : collection.find(query)) {
		System.out.println(doc.toJson());
	}
}
----[ List All Items with manufacturer=Cuisinart or manufacturer=Mr. Coffee 
]----
{ "_id" : "1454163779", "item-id" : "B0047Y0UQO", "description" : "Mr. Coffee 
BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome", "manufacturer" : "Mr. 
Coffee", "dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 29.74, "list_price" : 39.99, 
"quantity" : 13 }
{ "_id" : "1454164107", "item-id" : "B0008JIW8U", "description" : "Mr. Coffee 
DRX5 4-Cup Programmable Coffeemaker, Black", "manufacturer" : "Mr. Coffee", 
"dept" : "kitchen", "category" : "Coffee Machines", "sub-category" : 
"Programmable Coffee Makers", "price" : 24.99, "list_price" : 19.99, 
"quantity" : 32 }
{ "_id" : "1454163344", "item-id" : "B003KYSLMC", "description" : "Cuisinart 
CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, 
Black/Stainless", "manufacturer" : "Cuisinart", "dept" : "kitchen", "category" 
: "Coffee Machines", "sub-category" : "Programmable Coffee Makers", "price" : 
185.0, "list_price" : 91.89, "quantity" : 18 }
{ "_id" : "1454163348", "item-id" : "B000T9SCZ2", "description" : "Cuisinart 
DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black", 
"manufacturer" : "Cuisinart", "dept" : "kitchen", "category" : "Coffee 
Machines", "sub-category" : "Built-in Griders", "price" : 305.0, "list_price" 
: 159.99, "quantity" : 6 }
{ "_id" : "1454163351", "item-id" : "B0037ZG3DS", "description" : "Mr. Coffee 
BVMC-PSTX91 Optimal Brew 10-Cup Thermal Coffeemaker, Black/Stainless Steel", 
"manufacturer" : "Mr. Coffee", "department" : "kitchen", "category" : "Coffee 
Machines", "sub-category" : "Thermal Carafe", "price" : 69.0, "list-price" : 
89.99, "quantity" : 3 }

The Complete Program (MongoDBQueryExample.java)

package com.avaldes.tutorial;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.avaldes.model.Item;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBQueryExample {
  public static void main(String[] args) {
    mongoTestQueryOperations();
  }

  public static void mongoTestQueryOperations() {
    MongoClient mongoClient = null;

    try {
      System.out.println(
          "Using mongoTestQueryOperations() to 'test' database...");
      mongoClient = new MongoClient();
      MongoDatabase db = mongoClient.getDatabase("test");

      MongoCollection<Document> collection = db.getCollection("inventory");

      showAllDocuments(collection);
      findPriceGreaterThanQuery(collection, 95);
      findPriceLessThanQuery(collection, 100);
      findPriceInRangeQuery(collection, 90, 300);
      findQuantityGreaterThanEqualQuery(collection, 21);
      findSubCategoryNotEqualToQuery(collection, "Built-in Grinders");

      // Find only items on this list
      List<String> items = new ArrayList<String>();
      items.add("B003TOAM98");
      items.add("B000T9SCZ2");
      items.add("B002IASYA8");
      items.add("B0037ZG3DS");

      findItemIdInListQuery(collection, items);
      findItemIdNotInListQuery(collection, items);
      findItemLogicalAndQuery(collection, "Cuisinart", "kitchen");
      findItemLogicalOrQuery(collection, "Cuisinart", "Mr. Coffee");

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      mongoClient.close();
    }
  }

  private static void showAllDocuments(
      final MongoCollection<Document> collection) {

    System.out.println("----[ Show All Items ]----");
    for (Document doc : collection.find()) {
      System.out.println(doc.toJson());
    }
  }

  private static void findPriceGreaterThanQuery(
      final MongoCollection<Document> collection, final double price) {

    BasicDBObject query = new BasicDBObject();
    query.put("price", new BasicDBObject("$gt", price));

    System.out.println(String.format(
        "----[ List All Items Price Greater than %1$,.2f ]----", price));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findPriceLessThanQuery(
      final MongoCollection<Document> collection, final double price) {

    BasicDBObject query = new BasicDBObject();
    query.put("price", new BasicDBObject("$lt", price));

    System.out.println(String.format(
        "----[ List All Items Price Less than %1$,.2f ]----", price));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findQuantityGreaterThanEqualQuery(
      final MongoCollection<Document> collection, final int quantity) {

    BasicDBObject query = new BasicDBObject();
    query.put("quantity", new BasicDBObject("$gte", quantity));

    System.out.println(String.format(
        "----[ List All Items Quantity Greater than or Equal to %d ]----",
        quantity));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findPriceInRangeQuery(
      final MongoCollection<Document> collection, final double lowPrice,
      final double highPrice) {

    BasicDBObject query = new BasicDBObject();
    query.put("price",
        new BasicDBObject("$gte", lowPrice).append("$lte", highPrice));

    System.out.println(String.format(
        "----[ List All Items Price Greater than or Equal to %1$,.2f "
            + "and Less Than or Equal to %2$,.2f ]----",
        lowPrice, highPrice));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findSubCategoryNotEqualToQuery(
      final MongoCollection<Document> collection,
      final String subCategory) {

    BasicDBObject query = new BasicDBObject();
    query.put("sub-category", new BasicDBObject("$ne", subCategory));

    System.out.println(String.format(
        "----[ List All Items whose sub-category Not Equal to '%s' ]----",
        subCategory));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findItemIdInListQuery(
      final MongoCollection<Document> collection,
      final List<String> items) {

    BasicDBObject query = new BasicDBObject();
    query.put("item-id", new BasicDBObject("$in", items));

    System.out.println(String.format(
        "----[ List All Items whose item-id IN '%s' ]----", items));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findItemIdNotInListQuery(
      final MongoCollection<Document> collection,
      final List<String> items) {

    BasicDBObject query = new BasicDBObject();
    query.put("item-id", new BasicDBObject("$nin", items));

    System.out.println(String.format(
        "----[ List All Items whose item-id NOT IN '%s' ]----", items));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findItemLogicalAndQuery(
      final MongoCollection<Document> collection,
      final String manufacturer, final String department) {

    BasicDBObject query = new BasicDBObject();
    List<BasicDBObject> andQuery = new ArrayList<BasicDBObject>();
    andQuery.add(new BasicDBObject("manufacturer", manufacturer));
    andQuery.add(new BasicDBObject("dept", department));
    query.put("$and", andQuery);

    System.out.println(String.format(
        "----[ List All Items with manufacturer=%s AND department=%s ]----",
        manufacturer, department));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }

  private static void findItemLogicalOrQuery(
      final MongoCollection<Document> collection,
      final String manufacturer, final String manufacturer1) {

    BasicDBObject query = new BasicDBObject();
    List<BasicDBObject> orQuery = new ArrayList<BasicDBObject>();
    orQuery.add(new BasicDBObject("manufacturer", manufacturer));
    orQuery.add(new BasicDBObject("manufacturer", manufacturer1));
    query.put("$or", orQuery);

    System.out.println(String.format(
        "----[ List All Items with manufacturer=%s or manufacturer=%s ]----",
        manufacturer, manufacturer1));
    for (Document doc : collection.find(query)) {
      System.out.println(doc.toJson());
    }
  }
}

The Model (Item.java)

package com.avaldes.model;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;

@JsonPropertyOrder({"_id", "item-id", "description", 
                    "manufacturer", "dept", "category", 
                    "sub-category", "price", "list-price", "quantity"}) 
public class Item {
  private String id;
  private String itemId;
  private String description;
  private String manufacturer;
  private String department;
  private String category;
  private String subCategory;
  private double price;
  private double listPrice;
  private int quantity;

  @JsonProperty("_id")
  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  @JsonProperty("item-id")
  public String getItemId() {
    return itemId;
  }

  public void setItemId(String itemId) {
    this.itemId = itemId;
  }

  @JsonProperty("description")
  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  @JsonProperty("manufacturer")
  public String getManufacturer() {
    return manufacturer;
  }

  public void setManufacturer(String manufacturer) {
    this.manufacturer = manufacturer;
  }

  @JsonProperty("dept")
  public String getDepartment() {
    return department;
  }

  public void setDepartment(String department) {
    this.department = department;
  }

  @JsonProperty("category")
  public String getCategory() {
    return category;
  }

  public void setCategory(String category) {
    this.category = category;
  }

  @JsonProperty("sub-category")
  public String getSubCategory() {
    return subCategory;
  }

  public void setSubCategory(String subCategory) {
    this.subCategory = subCategory;
  }

  @JsonProperty("price")
  public double getPrice() {
    return price;
  }

  public void setPrice(double price) {
    this.price = price;
  }

  @JsonProperty("list-price")
  public double getListPrice() {
    return listPrice;
  }

  public void setListPrice(double listPrice) {
    this.listPrice = listPrice;
  }

  @JsonProperty("quantity")
  public int getQuantity() {
    return quantity;
  }

  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }

  @Override
  public String toString() {
    return "Item [id=" + id + ", itemId=" + itemId + ", description="
        + description + ", manufacturer=" + manufacturer + ", department="
        + department + ", category=" + category + ", subCategory="
        + subCategory + ", price=" + price + ", listPrice=" + listPrice
        + ", quantity=" + quantity + "]";
  }
}

JSON Sample Documents

I have included these JSON Documents as reference and to allow you to easily create the Mongo collection locally.

{
    "_id" : "1454163779",
    "item-id" : "B0047Y0UQO",
    "description" : "Mr. Coffee BVMC-SJX33GT 12-Cup Programmable Coffeemaker, Chrome",
    "manufacturer" : "Mr. Coffee",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 29.74,
    "list-price" : 39.99,
    "quantity" : 13
}
{
    "_id" : "1454164107",
    "item-id" : "B0008JIW8U",
    "description" : "Mr. Coffee DRX5 4-Cup Programmable Coffeemaker, Black",
    "manufacturer" : "Mr. Coffee",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 24.99,
    "list-price" : 19.99,
    "quantity" : 32
}
{
    "_id" : "1454163343",
    "item-id" : "B001NXC5YC",
    "description" : "Black & Decker DCM600B 5-Cup Coffeemaker, Black",
    "manufacturer" : "Black & Decker",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 19.99,
    "list-price" : 14.96,
    "quantity" : 65
}
{
    "_id" : "1454163344",
    "item-id" : "B003KYSLMC",
    "description" : "Cuisinart CHW-12 Coffee Plus 12-Cup Programmable Coffeemaker with Hot Water System, Black/Stainless",
    "manufacturer" : "Cuisinart",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 185.00,
    "list-price" : 91.89,
    "quantity" : 18
}
{
    "_id" : "1454163345",
    "item-id" : "B003TOAM98",
    "description" : "DeLonghi DCF2212T 12-Cup Glass Carafe Drip Coffee Maker, Black",
    "manufacturer" : "DeLonghi",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 70.00,
    "list-price" : 53.99,
    "quantity" : 21
}
{
    "_id" : "1454163346",
    "item-id" : "B001A61BMO",
    "description" : "Kalorik 1000-Watt 12-Cup Programmable Coffeemaker, Copper",
    "manufacturer" : "Kalorik",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Programmable Coffee Makers",
    "price" : 99.99,
    "list-price" : 36.95,
    "quantity" : 26
}
{
    "_id" : "1454163348",
    "item-id" : "B000T9SCZ2",
    "description" : "Cuisinart DGB-700BC Grind-and-Brew 12-Cup Automatic Coffeemaker, Brushed Chrome/Black",
    "manufacturer" : "Cuisinart",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Built-in Griders",
    "price" : 305.00,
    "list-price" : 159.99,
    "quantity" : 6
}
{
    "_id" : "1454163349",
    "item-id" : "B002EVOVPI",
    "description" : "Capresso 464.05 CoffeeTeam GS 10-Cup Digital Coffeemaker with Conical Burr Grinder",
    "manufacturer" : "Capresso",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Built-in Griders",
    "price" : 250.00,
    "list-price" : 164.99,
    "quantity" : 4
}
{
    "_id" : "1454163350",
    "item-id" : "B002IASYA8",
    "description" : "Cuisinart Fully Automatic Burr Grind & Brew Thermal 12 Cup Coffeemaker DGB900BCC",
    "manufacturer" : "Cuisinart",
    "dept" : "kitchen",
    "category" : "Coffee Machines",
    "sub-category" : "Built-in Griders",
    "price" : 249.99,
    "list-price" : 189.99,
    "quantity" : 6
}

Download the Complete Source Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_query_mongodb

Related Spring Posts

  • Creating Hello World Application using Spring MVC on Eclipse IDE
    In this tutorial we will go into some detail on how to set up your Eclipse IDE environment so that you can develop Spring MVC projects. In this post, we will create our first Spring MVC project with the all to familiar “Hello World” sample program.
  • Spring MVC Form Handling Example
    The following tutorial will guide you on writing a simple web based application which makes use of forms using Spring Web MVC framework. With this web application you will be able to interact with the customer entry form and enter all of the required values and submit them to the backend processes. I have taken the liberty of using CSS to beautify and transform the HTML page from a standard drab look and feel to a more appealing view.
  • Spring @RequestHeader Annotation Example
    In this tutorial, we will discuss the different ways that Spring MVC allow us to access HTTP headers using annotation. We will discuss how to access individual header fields from the request object as well accessing all the headers by supplying Map and then iterating through the LinkedHashMap collection. We will also show you how to set the headers in the response object.
  • Spring MVC Exception Handling using @ExceptionHandler with AngularJS GUI
    Good exception handling is a essential part of any well developed Application Framework and Spring MVC is no exception — pardon the pun. Spring MVC provides several different ways to handle exceptions in our applications. In this tutorial, we will cover Controller Based Exception Handling using the @ExceptionHandler annotation above the method that will handle it.
  • Spring RESTful Web Service Example with JSON and Jackson using Spring Tool Suite
    For this example, I will be using Spring Tool Suite (STS) as it is the best integrated development environment for building the Spring framework projects. Spring is today's leading framework for building Java, Enterprise Edition (Java EE) applications. One additional feature that makes Spring MVC so appealing is that it now also supports REST (REpresentational State Transfer) for build Web Services.
  • Spring MVC RESTful Web Service Example with Spring Data for MongoDB and ExtJS GUI
    This post will show another example of how to build a RESTful web service using Spring MVC 4.0.6, Spring Data for MongoDB 1.6.1 so that we can integrate the web application with a highly efficient datastore (MongoDB 2.6). In this tutorial we will walk you through building the web service and NoSQL database backend and show you how to implement CRUD (Create, Read, Update and Delete) operations.
  • Building DHTMLX Grid Panel User Interface with Spring MVC Rest and MongoDB Backend
    In this tutorial we will show how easy it is to use DHTMLX dhtmlxGrid component while loading JSON data with Ajax pulling in data from the Spring MVC REST web service from our MongoDB data source. You will see how simple it is to create a visually appealing experience for your client(s) with minimal javascript coding.
  • Spring MVC with JNDI Datasource for DB2 on AS/400 using Tomcat
    In this tutorial we will discuss how to set up Spring MVC web services and configure a JNDI Datasource using Tomcat and connect to IBM DB2 Database on a AS/400. JNDI (Java Naming and Directory Interface) provides and interface to multiple naming and directory services.
  • Java Spring MVC Email Example using Apache Velocity
    In this tutorial we will discuss how to set up a Java Spring MVC RESTful Webservice with Email using Apache Velocity to create a Velocity template that is used to create an HTML email message and embed an image, as shown below, using MIME Multipart Message.
  • Implementing Basic and Advanced Search using Angular Material Design, Grid-UI, Spring MVC REST API and MongoDB Example
    In this tutorial we will discuss how to implement basic and advanced search techniques in MongoDB using AngularJS and Google’s Material Design with Spring MVC REST API backend. The advanced search user interface (UI) will use logical operators and build a JSON object which contains the search field name, boolean or logical operator and the search value.
  • Spring MVC Interceptor using HandlerInterceptorAdapter Example
    In this tutorial we will discuss how to use the HandlerInterceptorAdapter abstract class to create a Spring MVC interceptor. These interceptors are used to apply some type of processing to the requests either before, after or after the complete request has finished executing.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *