Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

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.

As always, the complete code for all the examples is available over on GitHub.

NoSql Bottom

Build a Dashboard Using Cassandra, Astra, and Stargate

>> CHECK OUT THE ARTICLE
Persistence bottom

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

>> CHECK OUT THE COURSE
Persistence footer banner
guest
0 Comments
Inline Feedbacks
View all comments