Lesson 3: Querying a MongoDB Collection in Java Applications / Learn

Video Transcript (English)

Hello!

In this video, we’ll explore the find() and find().first() methods. These methods are used to retrieve documents from a MongoDB collection in a Java application.

We’ll also examine how query predicates allow us to define more efficient queries by using the Filters builder class.

The first query we’ll define uses the accounts collection. Say we want to find all accounts that have a balance greater than or equal to 1000. Before we start writing this query, it’s important to note that the query specifies two conditions: that the balance is greater than or equal to 1000, and that the account type is checking.

Query conditions, also known as predicates, are expressed as filters by using the Filters class. To create this query, we’ll use find().

For this video, we’ll assume that we have already instantiated the MongoClient and MongoCollection instances.

The MongoCollection class provides an overloaded find() method that accepts a filter. The find method returns a FindIterable<Document> that allows us to iterate the results of the query.

If we want to process each document that’s returned from the find() method, we can iterate the MongoCursor. We iterate by using a while loop in a try-with resources block.

In certain cases, we might only want to return a single document from a query. The MongoCollection object returns a single document with the find().first() method chain.

All queries that you run in MongoDB should specify a filter to avoid returning all the documents from a collection. Filtered queries optimize your applications' use of server resources, such as RAM, network, disk I/O, and CPU).

Well done!

In this video, you learned how to specify and filter queries when finding documents in MongoDB. We used the find() and find().first() method chain to search for documents with the help of the Filters class.