MongoDB filter in condition

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:

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"
}]);
0

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”:

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"
}]);
1

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”:

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"
}]);
2

4.6. exists() Method

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

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"
}]);
3

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:

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"
}]);
4

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.

How to write filter condition in MongoDB?

You can use the following conditions in the cond parameter for MongoDB Filtering:.
Greater than ((>) or $gt).
Less than ((<) or $lt).
Greater than equal to ((>=) or $gte).
Less than equal to ((<=) or $lte).

How to filter multiple conditions in MongoDB?

How do I filter a MongoDB collection by multiple fields? In MongoDB we filter by mutiple fields by separating the different fields we want to use as a filter by comas. There is an $and operator, but in this simple scenario we can leave it implicit.

How to find data with condition in MongoDB?

To find documents that match a set of selection criteria, call find() with the <criteria> parameter. MongoDB provides various query operators to specify the criteria. For a list of the query operators, see Query Selectors.

How to use $filter in MongoDB?

In the Filter field, enter a filter document. You can use all of the MongoDB query operators except the $text and $expr operators. Example. The following filter only returns documents which have a title value of Jurassic Park : ... .
Click Find to run the query and view the updated results. click to enlarge..