How To Use The AND Operator in MongoDB Queries using Java
Introduction
Creating queries is an integral part of communicating with MongoDB. Some queries are quite simple, while others are more complex and use logical operators such as AND
. If you’re a Java developer, the MongoDB Filters class can make it easy to use various logical operators in your MongoDB queries. In Java, you can pass an instance of a filter
object to the find()
method used to perform queries. This allows you to query for documents that meet a certain set of conditions. In this step-by-step tutorial, we’ll explain how to create queries that include logical operators with MongoDB filters.
Prerequisites
Before we can turn our attention to the Java code, it’s important to review the prerequisites for this tutorial. The system requirements for this task are minimal:
- You’ll need to make sure that both MongoDB and the MongoDB Java driver are installed and configured before proceeding.
Starting the MongoDB Daemon
Once you’ve confirmed that you’ve met the system requirements, the next step will be to start up MongoDB. If you don’t have a terminal window open, press Ctrl + Alt + T to open one up. Then, you can start up MongoDB and check its status using the command shown below. It’s best to use sudo
with this command to avoid permissions-related issues:
1 2 | sudo systemctl start mongod sudo systemctl status mongod |
You’ll see something like this as output:
1 2 3 4 5 6 7 8 9 | ● mongod.service - MongoDB Database Server Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: Active: active (running) since Sat 2019-05-18 10:10:52 PST; 2s ago Docs: https://docs.mongodb.org/manual Main PID: 8408 (mongod) CGroup: /system.slice/mongod.service └─8408 /usr/bin/mongod --config /etc/mongod.conf May 18 10:10:52 user-UX330UAK systemd[1]: Started MongoDB Database Server. |
Sample dataset for a MongoDB collection
In order to perform our example queries, we’ll need a dataset to work with. We’ll be using the following sample dataset when we query MongoDB, which consists of different restaurant dishes and their prices in U.S. dollars:
Name | Category | Menu Reference ID | Price (USD) |
---|---|---|---|
Southwest Quesadilla with Cilantro-Lime Sour Cream | appetizer | m01 | 35 |
Spicy Guacamole | appetizer | m01 | 20 |
Kiran | appetizer | m01 | 35 |
Mini Taco Dip Tostadas with Avocado Cream | appetizer | m01 | 35 |
Kelsey’s Signature SalsaSouthwest Quesadilla with Cilantro-Lime Sour Cream | appetizer | m01 | 25 |
Combining MongoDB queries using the Filter class
At this point, we can start looking at some Java code. Let’s begin with the following code segment:
1 2 3 | MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); MongoDatabase db = mongo.getDatabase("menuDB"); MongoCollection<document> colMenu = db.getCollection("menuAppetizer"); |
The code shown above connects to the MongoDB deployment and gets access to the database and the specified collection.
Now, let’s see how we can use the Filters class with MongoDB:
1 2 3 4 5 6 7 8 | Bson filter = Filters.and( Filters.ne("priceUsd", 25), Filters.ne("priceUsd", 20)); MongoCursor<document> cursor = colMenu.find(filter).iterator(); while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } |
In the code shown above, the methods found in the Filters class allows the user to use logical operators such as and
and ne
. Two query clauses are defined using the ne
method of the Filters class– we want priceUsd
to “not equal 25”, and we also want priceUsd
to “not equal 20”. You can see that both those query clauses are passed into the and
method of the Filters class, thus joining them together. This means that BOTH of those criteria must be met in order to be a match for this query.
This query, created using the Filters class, would return the following results. You can see that none of the results have a priceUsd
of either 20 or 25, proving that our query executed successfully:
1 2 3 4 | { "_id" : { "$oid" : "5cdd40773fd48a7157399968" }, "category" : "appetizer", "menu_Refid" : "m01", "priceUsd" : 35, "appetizerName" : "Southwest Quesadilla with Cilantro-Lime Sour Cream" } { "_id" : { "$oid" : "5cdd44623fd48a72c9300225" }, "category" : "appetizer", "menu_Refid" : "m01", "priceUsd" : 35, "appetizerName" : "Kiran" } { "_id" : { "$oid" : "5cdd44bf3fd48a730ccdc2af" }, "category" : "appetizer", "menu_Refid" : "m01", "priceUsd" : 35, "appetizerName" : "Mini Taco Dip Tostadas with Avocado Cream" } { "_id" : { "$oid" : "5cdd47003fd48a73c4dd84e7" }, "category" : "appetizer", "menu_Refid" : "m01", "priceUsd" : 35, "appetizerName" : "Mini Taco Dip Tostadas with Avocado Cream" } |
Conclusion
If you’re working with MongoDB to store and manage data, it’s important to know how to formulate queries. For Java developers, the Filters class makes it easy to use logical operators such as AND in a MongoDB query. With the examples provided in this tutorial, you’ll have no trouble creating queries that include logical operators with MongoDB filters.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started