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

Querying a MongoDB Collection in Java Applications

Review the following code, which demonstrates how to query documents in MongoDB with Java.

Using find()

In the following example, we find all accounts that have a balance greater than or equal to 1000 and are checking accounts. We process each document that’s returned from the find() method by iterating the MongoCursor. The find() method accepts a query filter and returns documents that match the filter in the collection.

MongoDatabase database = mongoClient.getDatabase("bank");
MongoCollection<Document> collection = database.getCollection("accounts");
try(MongoCursor<Document> cursor = collection.find(and(gte("balance", 1000),eq("account_type","checking")))
        .iterator())
{
    while(cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
}

Using find().first()

Chaining together the find() and first() methods finds the first matching document for the query filter that's passed into the find() method. In the following example, we return a single document from the same query:

MongoDatabase database = mongoClient.getDatabase("bank");
MongoCollection<Document> collection = database.getCollection("accounts");
Document doc = collection.find(Filters.and(gte("balance", 1000), Filters.eq("account_type", "checking"))).first();
System.out.println(doc.toJson());