eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this tutorial, we’ll learn how to use Filters builders to specify filters for queries in MongoDB.

The Filters class is a type of builder that helps us build query filters. Filters are operations MongoDB uses to limit the results based on a specific condition.

2. Types of Builders

The Java MongoDB Driver provides various types of builders that help us construct BSON documents. Builders provide a convenient API to simplify the process of performing various CRUD and aggregation operations.

Let’s review the different types of builders available:

  • Filters for building query filters
  • Projections for building field projection, specifying which fields to include and exclude
  • Sorts for building sorting criteria
  • Updates for building update operations
  • Aggregates for building aggregation pipelines
  • Indexes for building index keys

Let’s now take a deep dive into different ways to use Filters in MongoDB.

3. Database Initialization

Firstly, to demonstrate various filter operations, let’s set up a database baeldung and a sample collection, user:

use baeldung;
db.createCollection("user");

Further, let’s populate a few documents into the user collection:

db.user.insertMany([
{
    "userId":"123",
    "userName":"Jack",
    "age":23,
    "role":"Admin"
},
{
    "userId":"456",
    "userName":"Lisa",
    "age":27,
    "role":"Admin",
    "type":"Web"
},
{
    "userId":"789",
    "userName":"Tim",
    "age":31,
    "role":"Analyst"
}]);

Upon successful insertion, the above query would return a response acknowledging the result:

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("6357c4736c9084bcac72eced"),
        ObjectId("6357c4736c9084bcac72ecee"),
        ObjectId("6357c4736c9084bcac72ecef")
    ]
}

We’ll use this collection as a sample for all our filter operation examples.

4. Using the Filters Class

As already mentioned, Filters are operations the MongoDB uses to limit the results to what we want to see. The Filters class provides various static factory methods for different types of MongoDB operations. Each method returns a BSON type, which can then be passed to any method that expects a query filter.

The Filters class in the current MongoDB Java Driver API replaces the QueryBuilder from the Legacy API.

Filters are categorized based on the type of operation: conditional, logical, arrays, elements, evaluation, bitwise, and geospatial.

Next, let’s take a look at some of the most commonly used Filters methods.

4.1. eq() Method

The Filters.eq() method creates a filter that matches all the documents where the value of the specified field equals the specified value.

First, let’s look at the MongoDB Shell query to filter user collection documents where the userName equals “Jack”:

db.getCollection('user').find({"userName":"Jack"})

The query above returns a single document from the user collection:

{
    "_id" : ObjectId("6357c4736c9084bcac72eced"),
    "userId" : "123",
    "userName" : "Jack",
    "age" : 23.0,
    "role" : "Admin"
}

Now, let’s look at the corresponding MongoDB Java Driver code:

Bson filter = Filters.eq("userName", "Jack");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

We can notice that the Filters.eq() method returns a BSON type, which we are then passing to the find() method as the filter.

Also, Filters.ne() is just the opposite of the Filters.eq() method — it matches all the documents where the value of the named field doesn’t equal the specified value:

Bson filter = Filters.ne("userName", "Jack");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

4.2. gt() Method

The Filters.gt() method creates a filter that matches all the documents where the value of the specified field is greater than the specified value.

Let’s look at an example:

Bson filter = Filters.gt("age", 25);
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

The above code snippet fetches all user collection documents where the age is greater than 25. Just like the Filters.gt() method, there’s also a Filters.lt() method that matches all the documents where the value of the named field is less than the specified value:

Bson filter = Filters.lt("age", 25);
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Also, there are methods Filters.gte() and Filters.lte() that match values greater than or equal to and less than or equal to the specified value, respectively.

4.3. in() Method

The Filters.in() method creates a filter that matches all the documents where the value of the specified field equals any value in the list of specified values.

Let’s see it in action:

Bson filter = Filters.in("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

This code snippet fetches all user collection documents where the userName equals either “Jack” or “Lisa”.

Just like the Filters.in() method, there’s a Filters.nin() method that matches all the documents where the value of the named field doesn’t equal any value in the list of specified values:

Bson filter = Filters.nin("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

4.4. and() Method

The Filters.and() method creates a filter that performs a logical AND operation for the provided list of filters.

Let’s find all the user collection documents where the age is greater than 25 and the role equals “Admin”:

Bson filter = Filters.and(Filters.gt("age", 25), Filters.eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

4.5. or() Method

As we’d expect, the Filters.or() method creates a filter that performs a logical OR operation for the provided list of filters.

Let’s write a code snippet that returns all the user collection documents where the age is greater than 30 or the role equals “Admin”:

Bson filter = Filters.or(Filters.gt("age", 30), Filters.eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

4.6. exists() Method

Further, the Filters.exists() method creates a filter that matches all documents that contain the given field:

Bson filter = Filters.exists("type");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

The code above returns all the user collection documents that have a type field.

4.7. regex() Method

Finally, the Filters.regex() method creates a filter that matches documents where the value of the specified field matches the given regular expression pattern:

Bson filter = Filters.regex("userName", "a");
FindIterable<Document> documents = collection.find(filter);

MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Here, we fetched all user collection documents where the userName matches the regex “a”.

So far, we’ve discussed some of the most commonly used filter operators. We can use any combination of the query filter operators as a filter for the find() method.

Moreover, filters can be used at various other places such as the match stage of aggregation, deleteOne() method, and updateOne() method, to name a few.

5. Conclusion

In this article, we first discussed how to use Filters builders to perform filter operations on a MongoDB collection. We then saw how to implement some of the most commonly used filter operations using the MongoDB Java Driver API.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)