What You Will Learn:
- How to connect Java to MongoDB.
- How to query documents from a MongoDB collection.
- How to apply filters, sort, and limit the results.
Technologies Used:
- JDK: Version 21
- MongoDB: Version 6.0 or later
- MongoDB Java Driver: Version 5.1.4
Step 1: Add MongoDB Java Driver Dependency
To query MongoDB, you need to add the MongoDB Java Driver to your project.
For Maven Users:
Add the following dependency to your pom.xml
file:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.1.4</version>
</dependency>
For Gradle Users:
Add the following line to your build.gradle
file:
implementation 'org.mongodb:mongodb-driver-sync:5.1.4'
If you are not using Maven or Gradle, download the MongoDB Java Driver JAR file and manually add it to your classpath.
Step 2: Write Java Code to Query Documents
Here’s a Java program that demonstrates various queries on a MongoDB collection.
Code Example:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
public class MongoDBQueryExample {
private static final String URI = "mongodb://localhost:27017";
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create(URI)) {
// Step 1: Access the database
MongoDatabase database = mongoClient.getDatabase("mydb");
// Step 2: Access the collection
MongoCollection<Document> collection = database.getCollection("employees");
// Query 1: Find documents where department is "IT"
System.out.println("Query 1: Employees in IT department:");
MongoCursor<Document> cursor = collection.find(Filters.eq("department", "IT")).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
// Query 2: Find documents where age is greater than 30
System.out.println("\nQuery 2: Employees older than 30:");
cursor = collection.find(Filters.gt("age", 30)).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
// Query 3: Sort by age in descending order and limit to 3 results
System.out.println("\nQuery 3: Top 3 oldest employees:");
cursor = collection.find()
.sort(Sorts.descending("age"))
.limit(3)
.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
// Query 4: Find employees in "IT" or "HR" department
System.out.println("\nQuery 4: Employees in IT or HR department:");
cursor = collection.find(Filters.or(Filters.eq("department", "IT"), Filters.eq("department", "HR"))).iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation with Code Snippets:
Step 1: Access the Database The
getDatabase()
method is used to access or create a database calledmydb
.MongoDatabase database = mongoClient.getDatabase("mydb");
Step 2: Access the Collection The
getCollection()
method is used to access theemployees
collection.MongoCollection<Document> collection = database.getCollection("employees");
Query 1: Filter by Department (Equality Query)
This query finds all employees where the department is "IT"
.
MongoCursor<Document> cursor = collection.find(Filters.eq("department", "IT")).iterator();
Filters.eq("field", value)
: Finds documents where a specific field equals the given value.
Query 2: Filter by Age Greater Than (Comparison Query)
This query retrieves employees who are older than 30.
cursor = collection.find(Filters.gt("age", 30)).iterator();
Filters.gt("field", value)
: Finds documents where a field is greater than the given value.
Query 3: Sort and Limit
This query sorts employees by age in descending order and limits the results to the top 3 oldest employees.
cursor = collection.find()
.sort(Sorts.descending("age"))
.limit(3)
.iterator();
Sorts.descending("field")
: Sorts the documents in descending order based on the field.limit(n)
: Limits the result set ton
documents.
Query 4: Use OR
Condition
This query retrieves employees who belong to either the "IT"
or "HR"
department.
cursor = collection.find(Filters.or(Filters.eq("department", "IT"), Filters.eq("department", "HR"))).iterator();
Filters.or()
: Combines multiple filters using logical OR.
Step 3: Run the Java Program
Once you write the code, run the program in your IDE or from the command line. The results for each query will be printed to the console, displaying matching documents from the MongoDB collection.
Step 4: Verify the Queries in MongoDB Shell
You can also verify the queries manually using the MongoDB shell:
use mydb
db.employees.find({ "department": "IT" })
db.employees.find({ "age": { $gt: 30 } })
db.employees.find({}).sort({ "age": -1 }).limit(3)
db.employees.find({ $or: [ { "department": "IT" }, { "department": "HR" } ] })
Conclusion
In this tutorial, you learned how to:
- Query documents in MongoDB using Java 21 and the MongoDB Java Driver.
- Apply various filters such as equality, comparison, sorting, limiting, and logical conditions.
- Iterate over the query results and process them in your application.
This guide provides the basic techniques for performing MongoDB queries using Java. Depending on your use case, you can further enhance these techniques by applying complex filters, projections, and aggregations.
Comments
Post a Comment
Leave Comment