How to Use the LIKE Query in MongoDB using Java
Introduction
When you’re querying a database, there are times when you need answers to questions that can’t be accomplished with typical operators. Perhaps you have a collection of student records, and you want to query for all names that start with “R”– you can’t rely on a traditional exact-matching query to do the job. In SQL, this type of task would be accomplished using the “LIKE” operator. While this operator isn’t used in MongoDB, the same results can be achieved using regular expressions. In this tutorial, we’ll talk more about regular expressions and show you how to construct the equivalent of a LIKE query in MongoDB using Java.
Prerequisites
Before we begin looking at any Java code, it’s important to review the system requirements for this task. There are a few key prerequisites that need to be in place:
First, you need to ensure that MongoDB and the MongoDB Java driver are both properly configured beforehand.
You must also ensure that the latest Java JDK is properly installed and configured beforehand.
Finally, you need to ensure that the MongoDB service is running.
NOTE: For the purposes of this tutorial, we will assume that the MongoDB version used is 4.0 and the MongoDB Java Driver is 3.8.2.
The MongoDB Dataset
It will be easier to follow along with the query examples presented in this article if you’re working with the same dataset. The data shown below will be used in this tutorial; you can use it to create your own sample dataset in MongoDB:
ID | Name | Rating | Country |
---|---|---|---|
5ceb7d233fd48a1ebd04318e | Chang Kai-shek | 11 | China |
5ceb7d233fd48a1ebd04318f | Sun Yat-sen | 8 | China |
5ceb7d233fd48a1ebd043190 | Muammar al-Gaddafi | 15 | Libya |
5ceb7d233fd48a1ebd043191 | Oda Nobunaga | 15 | Japan |
5ceb7d233fd48a1ebd043192 | Cao Cao | 19 | China |
5ceb7d233fd48a1ebd043193 | Sun Tzu | 10 | China |
Get access to the MongoDB Deployment
Now that we’ve reviewed all the system requirements and created a small sample dataset, we can start looking at some code. We’ll begin by instantiating a MongoClient object where we explicitly specify the hostname and the port number of our deployment:
1 | MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); |
Get access to the MongoDB Database
Next, we use the command shown below to access the MongoDB database using the getDatabase()
method. In this case, we’re accessing the "warlordDB"
database:
1 | MongoDatabase db = mongo.getDatabase("warlordDB"); |
Get access to the MongoDB Collection
We then use the following code to get access to a MongoDB collection. In this example, we access the "warlordCollection"
, which contains the sample data we looked at in the previous section:
1 | MongoCollection<document> warColl = db.getCollection("warlordCollection"); |
Query MongoDB collection using $regex to simulate the LIKE query for SQL engines.
If you’ve spent any time working with SQL, you know that you can use the LIKE
operator to search for matches based on a term that might be a partial match for a field. The same type of partial matching can be accomplished in MongoDB by leveraging “regular expressions” or simply regex
. A regular expression can be defined as a string that defines a search pattern. We’ll be making use of a regex
in the code shown below:
1 2 3 4 5 6 7 8 9 | BasicDBObject regexQuery = new BasicDBObject(); regexQuery.put("name", new BasicDBObject("$regex", "Su.*").append("$options", "i")); FindIterable<document> cursor = warColl.find(regexQuery); MongoCursor<document> iterator = cursor.iterator(); while (iterator.hasNext()) { iterator.next(); } cursor.forEach((Block<document>) System.out::println); |
Let’s take a look at what’s going on inside this code:
Note that the
BasicDBObject
is used to represent a MongoDB document.The
$regex
used in the query will be looking for a certain pattern as specified within theBasicDBObject
. In this case, we’re looking for names that begin with “Su”, which is expressed in the$regex
asSu.*
.We also appended the following option in the query:
("$options", "i")
. Using the flagi
indicates that the search will be case insensitive.The results should look like the following:
1 2 | Document{{_id=5cee629f3fd48a38b2d163be, name=Sun Yat-sen, country=China, rating=8}} Document{{_id=5cee629f3fd48a38b2d163c2, name=Sun Tzu, country=China, rating=10}} |
As you can see, the two results that were returned both have names that begin with “Su”, confirming that our partial-match query using regex
worked correctly.
Conclusion:
Anyone who has experience with SQL understands the power of the “LIKE” query– with this query, you can move beyond exact matching and locate matches based on words or phrases that may only partially match a field’s values. Although this exact operator is relegated to SQL and not used in MongoDB, it’s easy to get the same results by harnessing the power of regular expressions. With the instructions and examples shown in this article, you’ll be ready to create your own version of a LIKE query in MongoDB using Java.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started