How to Use MongoDB Comparison Query Operators in Java

Introduction

When you query a database, there are times when you need to use comparison operators to express the conditions of the query. You might want a list of all students whose age is greater than 16, or you might want the database to return all cars where the model year equals 2019. Queries like these are easy to create using MongoDB, but the exact syntax may be a bit unfamiliar if you’re used to working with SQL. In this step-by-step tutorial, we’ll provide instructions for using MongoDB comparison query operators in Java.

Prerequisites

Before we start looking at various comparison operators, it’s important to review the prerequisites for this task. There are a few key system requirements to consider:

  • You need to make sure that both MongoDB and the MongoDB Java driver are properly installed and configured.

  • You also need to confirm that the latest Java JDK has been installed and configured beforehand.

  • Finally, you need to confirm that the MongoDB service is running.

NOTE: Throughout this article, we’ll assume that the MongoDB version being used is 4.0 and the MongoDB Java Driver version is 3.8.2.

The MongoDB Dataset

If you’re planning on following along with the examples in this article, it’s best to be working with the same dataset. We’ll be using the dataset shown below in this tutorial:

IDNameRatingCountry
5ceb7d233fd48a1ebd04318eChang Kai-shek11China
5ceb7d233fd48a1ebd04318fSun Yat-sen8China
5ceb7d233fd48a1ebd043190Muammar al-Gaddafi15Libya
5ceb7d233fd48a1ebd043191Oda Nobunaga15Japan
5ceb7d233fd48a1ebd043192Cao Cao19China
5ceb7d233fd48a1ebd043193Sun Tzu10China

MongoDB Query Operators

MongoDB Query Operator $eq

The first operator we’ll be discussing is $eq. This operator denotes a equality condition. The $eq operator matches MongoDB documents where the value of a field equals the specified criteria.

Let’s look at an example of using the operator $eq in Java:

MongoDatabase db = mongo.getDatabase("warlordDB");

FindIterable<document> findIt = db.getCollection("warlordCollection").find(eq("name","Cao Cao"));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

NOTE : It’s recommended to include the static import for the method Filters.eq at the beginning of your code: import static com.mongodb.client.model.Filters.eq;.

The results should look like the following:

Document{{_id=5ceb7d233fd48a1ebd043192, name=Cao Cao, country=China}}

MongoDB Query Operator $gt

Next, we’ll look at the $gt operator. This operator selects documents where the field’s value is greater than the specified criteria. It’s similar to the >operator used in mathematics and SQL:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$gt" , 14)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

If we look at the dataset, we see that the results should look like the following, displaying all documents with a rating field greater than 14:

Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}

MongoDB Query Operator $lt

The operator $lt selects documents where the field’s value is less than the specified criteria. It’s similar to the < operator seen in mathematics and SQL:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$lt" , 14)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

In this example, we can look at our dataset and see that the result should look like the following, displaying all documents with a rating field less than 14:

Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db17470, name=Sun Tzu, country=China, rating=10}}

MongoDB Query Operator $gte

Now that we’ve covered “greater than” and “less than” operators, let’s move on to the $gte operator. This operator selects documents where the field’s value is greater than or equal to the specified criteria. In a SQL statement or mathematical expression, this operator would be represented as “>=”:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$gte" , 15)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

The code shown above returns documents that are greater than or equal to the value of the rating field.

The result will look something like this:

Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}

MongoDB Query Operator $lte

The operator $lte selects documents where the field’s value is less than or equal to the specified criteria. In a SQL statement or mathematical expression, this operator would be represented as “<=”:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$lte" , 15)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

The result should look something like this:

Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db17470, name=Sun Tzu, country=China, rating=10}}

MongoDB Query Operator $in

Now, let’s look at a somewhat different type of operator: $in. The $in operator will select documents where the value of a field matches a value in a specified array (e.g. <value1>, <value2>, and so on). Let’s look at an example:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$in", Arrays.asList(19,10))
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

In this query, we looked for documents where the value of rating matched one of the two values contained in the array [19,10]. The results should look something like this:

Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}
Document{{_id=5cebb0223fd48a338db17470, name=Sun Tzu, country=China, rating=10}}

MongoDB Query Operator $nin

The $nin operator will simply select values that are not in the specified criteria:

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$in", Arrays.asList(19,10))
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

In this example, we’re looking for documents where the value of rating is not one of the values contained in the array [19, 10]. The result should look something like this:

Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}

MongoDB Query Operator $ne

We began our examples with the $eq operator, and we’ll end with its opposite: the $ne operator. This operator simply selects values that are not equal to the specified criteria.

MongoDatabase db = mongo.getDatabase("warlordDB");
FindIterable<document> findIt = db.getCollection("warlordCollection").find( new Document()
.append("rating", new Document()
.append("$ne", 10)
));

MongoCursor<document> cursor = findIt.iterator();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

The result should look like the following:

Document{{_id=5cebb0223fd48a338db1746b, name=Chang Kai-shek, country=china, rating=11}}
Document{{_id=5cebb0223fd48a338db1746c, name=Sun Yat-sen, country=china, rating=8}}
Document{{_id=5cebb0223fd48a338db1746d, name=Muammar al-Gaddafi, country=Libya, rating=15}}
Document{{_id=5cebb0223fd48a338db1746e, name=Oda Nobunaga, country=Japan, rating=15}}
Document{{_id=5cebb0223fd48a338db1746f, name=Cao Cao, country=China, rating=19}}

Conclusion

Comparison operators are a staple of database queries, but the syntax used in MongoDB might seem a bit unfamiliar if you’re accustomed to SQL. Fortunately, the comparison query operators used in MongoDB are very easy to understand. With the examples and instructions provided in this tutorial, you’ll have no trouble using MongoDB comparison query operators in Java.

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.