This blog teaches you how to query one or more documents from a MongoDB collection using Java. You will learn how to use the find method, filters, projections, sorts, and aggregates.
1. Introduction
MongoDB is a popular open-source document-oriented database that stores data in JSON-like format. It is widely used for web applications, big data, and real-time analytics. MongoDB offers a flexible schema, high performance, scalability, and rich query functionality.
Java is one of the most widely used programming languages in the world. It is a general-purpose, object-oriented, and platform-independent language that runs on the Java Virtual Machine (JVM). Java is known for its portability, reliability, security, and concurrency.
In this blog, you will learn how to query one or more documents from a MongoDB collection using Java. You will use the MongoDB Java Driver, which is the official Java client library for MongoDB. You will learn how to use the find method, which is the primary method for querying documents from a collection. You will also learn how to use Filters, Projections, Sorts, and Aggregates to customize your queries and get the desired results.
By the end of this blog, you will be able to query documents from a MongoDB collection using Java with ease and confidence. You will also gain a deeper understanding of the MongoDB query language and its features.
Are you ready to get started? Let’s begin!
2. Setting Up the MongoDB Java Driver
The first step to query documents from a MongoDB collection using Java is to set up the MongoDB Java Driver. The MongoDB Java Driver is the official Java client library for MongoDB that provides a native Java API for interacting with MongoDB databases and collections. You can use the MongoDB Java Driver to perform CRUD (create, read, update, and delete) operations, as well as more advanced features such as aggregation, indexing, transactions, and change streams.
To set up the MongoDB Java Driver, you need to add it as a dependency to your Java project. There are different ways to do this, depending on the build tool you are using. In this blog, we will use Maven, which is a popular tool for managing Java dependencies and building Java applications. If you are using a different tool, you can refer to the official documentation for the instructions.
To add the MongoDB Java Driver as a Maven dependency, you need to edit the pom.xml file of your project and include the following snippet:
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.3.3</version> </dependency> </dependencies>
This will add the mongodb-driver-sync dependency, which is the synchronous version of the MongoDB Java Driver. This means that the driver will block the current thread until the operation is completed. There is also an asynchronous version of the driver, which is called mongodb-driver-async, that allows you to perform non-blocking operations using callbacks or reactive streams. You can choose the version that suits your needs, but in this blog, we will use the synchronous version for simplicity.
Once you have added the dependency, you can save the pom.xml file and run the mvn install command to install the MongoDB Java Driver in your local repository. Alternatively, you can use an IDE such as Eclipse or IntelliJ IDEA to automatically resolve the dependencies for you.
Congratulations! You have successfully set up the MongoDB Java Driver in your Java project. You are now ready to connect to a MongoDB database and start querying documents from a MongoDB collection.
3. Connecting to a MongoDB Database
Now that you have set up the MongoDB Java Driver, you can connect to a MongoDB database and access its collections. A MongoDB database is a logical grouping of collections, which are analogous to tables in relational databases. A collection is a set of documents, which are analogous to rows in relational databases. A document is a JSON-like object that contains key-value pairs, which are analogous to columns in relational databases.
To connect to a MongoDB database, you need to create a MongoClient object, which represents a connection pool to the database. You can use the MongoClients.create() method to create a MongoClient object with the default settings, which will connect to the local MongoDB instance running on port 27017. Alternatively, you can use the MongoClients.create(String connectionString) method to create a MongoClient object with a custom connection string, which can specify the host, port, username, password, and other options for the database. For example, the following code creates a MongoClient object that connects to a MongoDB Atlas cluster, which is a cloud-hosted MongoDB service:
// Replace the connection string with your own Atlas cluster connection string String connectionString = "mongodb+srv://:@/test?retryWrites=true&w=majority"; MongoClient mongoClient = MongoClients.create(connectionString);
Once you have created a MongoClient object, you can use the getDatabase(String databaseName) method to get a MongoDatabase object, which represents a MongoDB database. You can use the getCollection(String collectionName) method to get a MongoCollection object, which represents a MongoDB collection. For example, the following code gets a MongoDatabase object named “test” and a MongoCollection object named “users” from the MongoClient object:
MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection collection = database.getCollection("users");
You have successfully connected to a MongoDB database and accessed its collection. You are now ready to query documents from the collection using the MongoDB Java Driver.
4. Querying Documents from a MongoDB Collection
After connecting to a MongoDB database and accessing its collection, you can query documents from the collection using the MongoDB Java Driver. A query is a way of specifying the criteria and options for retrieving documents from a collection. You can use various methods and classes provided by the MongoDB Java Driver to construct and execute queries.
The primary method for querying documents from a collection is the find() method, which returns an iterable object that contains the matching documents. You can use the forEach(Consumer<? super TResult> block) method to iterate over the documents and perform some action on each document. For example, the following code queries all the documents from the “users” collection and prints them to the console:
collection.find().forEach(document -> System.out.println(document.toJson()));
By default, the find() method returns all the documents in the collection. However, you can also specify a filter to narrow down the results. A filter is a document that specifies the query criteria, such as the values or ranges of values for certain fields. You can use the Filters class to create filters using various operators, such as eq (equal), gt (greater than), and (logical and), and or (logical or). For example, the following code queries the documents from the “users” collection where the “age” field is greater than 25 and the “gender” field is equal to “female”:
collection.find(Filters.and(Filters.gt("age", 25), Filters.eq("gender", "female"))).forEach(document -> System.out.println(document.toJson()));
In addition to filters, you can also specify projections, sorts, and aggregates to customize your queries. Projections are a way of specifying which fields to include or exclude in the query results. Sorts are a way of ordering the query results by one or more fields. Aggregates are a way of performing complex queries that involve grouping, transforming, or analyzing the documents. You can use the Projections, Sorts, and Aggregates classes to create projections, sorts, and aggregates using various methods and operators. For example, the following code queries the documents from the “users” collection where the “age” field is greater than 25, projects only the “name” and “age” fields, sorts the results by the “age” field in descending order, and groups the results by the “name” field and calculates the average age for each name:
collection.find(Filters.gt("age", 25)) .projection(Projections.include("name", "age")) .sort(Sorts.descending("age")) .aggregate(Arrays.asList( Aggregates.group("$name", Accumulators.avg("averageAge", "$age")) )) .forEach(document -> System.out.println(document.toJson()));
You have learned how to query documents from a MongoDB collection using the MongoDB Java Driver. You have also learned how to use filters, projections, sorts, and aggregates to customize your queries and get the desired results. In the next sections, you will learn more about each of these features and how to use them effectively.
4.1. Using the find Method
The find() method is the primary method for querying documents from a MongoDB collection using the MongoDB Java Driver. It returns a FindIterable object, which implements the Iterable interface and allows you to iterate over the matching documents. You can use the forEach(Consumer<? super TResult> block) method to apply a consumer function to each document in the iterable. For example, you can use the System.out::println method as a consumer function to print each document to the console.
The find() method takes an optional parameter of type Bson, which represents a filter document that specifies the query criteria. If you omit the parameter, the find() method will return all the documents in the collection. If you provide a filter document, the find() method will return only the documents that match the filter. You can use the Filters class to create filter documents using various operators, such as eq (equal), gt (greater than), and (logical and), and or (logical or).
For example, suppose you have a collection named “users” that contains documents with the following schema:
{ "_id": ObjectId, "name": String, "age": Number, "gender": String, "email": String, "phone": String }
If you want to query all the documents from the “users” collection, you can use the following code:
MongoCollection collection = database.getCollection("users"); collection.find().forEach(System.out::println);
If you want to query the documents from the “users” collection where the “age” field is greater than 25, you can use the following code:
MongoCollection collection = database.getCollection("users"); collection.find(Filters.gt("age", 25)).forEach(System.out::println);
If you want to query the documents from the “users” collection where the “gender” field is equal to “female” and the “email” field contains the substring “gmail.com”, you can use the following code:
MongoCollection collection = database.getCollection("users"); collection.find(Filters.and(Filters.eq("gender", "female"), Filters.regex("email", "gmail.com"))).forEach(System.out::println);
You have learned how to use the find() method to query documents from a MongoDB collection using the MongoDB Java Driver. You have also learned how to use the Filters class to create filter documents using various operators. In the next section, you will learn how to use projections to specify which fields to include or exclude in the query results.
4.2. Using Filters to Specify Query Criteria
Filters are a way of specifying the query criteria for the find() method. A filter is a document that contains one or more operators and values that determine which documents match the query. You can use the Filters class to create filter documents using various operators, such as eq (equal), gt (greater than), and (logical and), and or (logical or).
The Filters class provides static methods that return Bson objects, which represent filter documents. You can pass these Bson objects as parameters to the find() method to apply the filters to the query. You can also combine multiple Bson objects using the and and or methods to create complex filters. For example, the following code creates a filter document that matches the documents where the “age” field is greater than 25 and the “gender” field is equal to “female”:
Bson filter = Filters.and(Filters.gt("age", 25), Filters.eq("gender", "female"));
The Filters class provides many other methods and operators that you can use to create filter documents. Some of the most common ones are:
- eq: Matches documents where the value of a field is equal to a specified value.
- ne: Matches documents where the value of a field is not equal to a specified value.
- gt: Matches documents where the value of a field is greater than a specified value.
- gte: Matches documents where the value of a field is greater than or equal to a specified value.
- lt: Matches documents where the value of a field is less than a specified value.
- lte: Matches documents where the value of a field is less than or equal to a specified value.
- in: Matches documents where the value of a field is in a specified array of values.
- nin: Matches documents where the value of a field is not in a specified array of values.
- exists: Matches documents where a field exists or does not exist.
- type: Matches documents where the type of a field is a specified BSON type.
- regex: Matches documents where the value of a field matches a specified regular expression.
- elemMatch: Matches documents where an array field contains an element that matches a specified filter document.
- size: Matches documents where an array field has a specified number of elements.
- all: Matches documents where an array field contains all the specified values.
- and: Matches documents where all the specified filter documents are true.
- or: Matches documents where any of the specified filter documents are true.
- not: Matches documents where the specified filter document is false.
- nor: Matches documents where none of the specified filter documents are true.
You can find more information and examples of using the Filters class and its methods in the official documentation.
You have learned how to use filters to specify query criteria for the find() method. You have also learned how to use the Filters class and its methods to create filter documents using various operators. In the next section, you will learn how to use projections to specify which fields to include or exclude in the query results.
4.3. Using Projections to Specify Fields to Return
Projections are a way of specifying which fields to include or exclude in the query results. A projection is a document that contains one or more field names and values that indicate whether to include or exclude the field. You can use the Projections class to create projection documents using various methods, such as include, exclude, elemMatch, and slice.
The Projections class provides static methods that return Bson objects, which represent projection documents. You can pass these Bson objects as parameters to the projection() method of the FindIterable object returned by the find() method to apply the projections to the query. You can also combine multiple Bson objects using the fields method to create complex projections. For example, the following code creates a projection document that includes only the “name” and “age” fields and excludes the “_id” field:
Bson projection = Projections.fields(Projections.include("name", "age"), Projections.excludeId());
The Projections class provides many other methods and operators that you can use to create projection documents. Some of the most common ones are:
- include: Includes the specified field(s) in the query results.
- exclude: Excludes the specified field(s) from the query results.
- excludeId: Excludes the “_id” field from the query results.
- elemMatch: Applies a filter document to an array field and projects only the first matching element.
- slice: Limits the number of elements projected from an array field.
- fields: Combines multiple projection documents into one.
You can find more information and examples of using the Projections class and its methods in the official documentation.
You have learned how to use projections to specify which fields to include or exclude in the query results. You have also learned how to use the Projections class and its methods to create projection documents using various operators. In the next section, you will learn how to use sorts to order the query results by one or more fields.
4.4. Using Sorts to Order the Query Results
Sorts are a way of ordering the query results by one or more fields. A sort is a document that contains one or more field names and values that indicate whether to sort the field in ascending or descending order. You can use the Sorts class to create sort documents using various methods, such as ascending, descending, orderBy, and metaTextScore.
The Sorts class provides static methods that return Bson objects, which represent sort documents. You can pass these Bson objects as parameters to the sort() method of the FindIterable object returned by the find() method to apply the sorts to the query. You can also combine multiple Bson objects using the orderBy method to create complex sorts. For example, the following code creates a sort document that orders the results by the “age” field in descending order and then by the “name” field in ascending order:
Bson sort = Sorts.orderBy(Sorts.descending("age"), Sorts.ascending("name"));
The Sorts class provides many other methods and operators that you can use to create sort documents. Some of the most common ones are:
- ascending: Sorts the results by the specified field(s) in ascending order.
- descending: Sorts the results by the specified field(s) in descending order.
- orderBy: Combines multiple sort documents into one.
- metaTextScore: Sorts the results by the text score assigned to each document by the $text operator.
You can find more information and examples of using the Sorts class and its methods in the official documentation.
You have learned how to use sorts to order the query results by one or more fields. You have also learned how to use the Sorts class and its methods to create sort documents using various operators. In the next section, you will learn how to use aggregates to perform complex queries that involve grouping, transforming, or analyzing the documents.
4.5. Using Aggregates to Perform Complex Queries
Aggregates are a way of performing complex queries that involve grouping, transforming, or analyzing the documents. An aggregate is a sequence of stages, each of which applies an operation to the documents that pass through it. You can use the Aggregates class to create aggregate stages using various methods, such as match, group, project, and sort.
The Aggregates class provides static methods that return Bson objects, which represent aggregate stages. You can pass these Bson objects as parameters to the aggregate(List<? extends Bson> pipeline) method of the MongoCollection object to apply the aggregates to the query. You can also combine multiple Bson objects using the Arrays.asList method to create a list of stages. For example, the following code creates an aggregate that groups the documents by the “gender” field and calculates the average age for each group:
Bson group = Aggregates.group("$gender", Accumulators.avg("averageAge", "$age")); Bson sort = Aggregates.sort(Sorts.descending("averageAge")); List pipeline = Arrays.asList(group, sort); collection.aggregate(pipeline).forEach(System.out::println);
The Aggregates class provides many other methods and operators that you can use to create aggregate stages. Some of the most common ones are:
- match: Filters the documents that match a specified filter document.
- group: Groups the documents by a specified expression and applies one or more accumulators to each group.
- project: Projects the documents by including, excluding, or modifying the fields.
- sort: Sorts the documents by one or more fields.
- limit: Limits the number of documents that pass through the stage.
- skip: Skips the specified number of documents that pass through the stage.
- unwind: Deconstructs an array field and outputs a document for each element.
- lookup: Performs a left outer join with another collection and adds the joined documents to an array field.
- out: Writes the documents to a specified collection.
You can find more information and examples of using the Aggregates class and its methods in the official documentation.
You have learned how to use aggregates to perform complex queries that involve grouping, transforming, or analyzing the documents. You have also learned how to use the Aggregates class and its methods to create aggregate stages using various operators. In the final section, you will learn how to conclude your blog and provide some useful resources for further learning.
5. Conclusion
You have reached the end of this blog on how to query documents from a MongoDB collection using Java. You have learned how to:
- Set up the MongoDB Java Driver in your Java project.
- Connect to a MongoDB database and access its collections.
- Use the find() method to query one or more documents from a collection.
- Use the Filters class to specify query criteria using various operators.
- Use the Projections class to specify which fields to include or exclude in the query results.
- Use the Sorts class to order the query results by one or more fields.
- Use the Aggregates class to perform complex queries that involve grouping, transforming, or analyzing the documents.
By following this blog, you have gained a deeper understanding of the MongoDB query language and its features. You have also gained practical skills on how to use the MongoDB Java Driver to interact with MongoDB databases and collections.
We hope you enjoyed this blog and found it useful for your learning. If you want to learn more about MongoDB and Java, here are some useful resources that you can check out:
- Quick Start: Java and MongoDB – Aggregation Pipeline: A tutorial that shows you how to use the aggregation pipeline to perform complex data analysis on MongoDB documents using Java.
- MongoDB Java Driver Documentation: The official documentation of the MongoDB Java Driver, which contains the API reference, examples, and guides.
- MongoDB Manual: The official documentation of MongoDB, which contains the reference, tutorials, and guides.
Thank you for reading this blog. We hope you have a great day and happy coding!