Search In MongoDB Using Java

In this post, we will learn to implement a search query in MongoDB using Java. Most of the applications have search functionality. So, learning to use it will be very useful.

1. Prerequisite

  • MongoDB installed
  • Java driver for MongoDB

2. SQL query example

select * from user where name like '%ai%';

This query fetches all the users whose name has a character ai together. It matches all the names given below:

Fraiser
Crug Air
Jaimin
Balam Jair
Isai
Again

3. MongoDB query in Java

The MongoDB query equivalent to search a single word in Java is:

Filters.regex("name","ai", "i")

The complete example:

String search = "ai";
Bson searchQuery = Filters.regex("name",search, "i");
/*
*The following code returns the FindIterable object of user collection.
*/
userCollection.find(searchQuery);

In our example, we can see that the “i” options parameter to ignore case sensitivity. In most of the search features, we usually ignore the case sensitive so I’ve used it in here. If you want to match the words with the exact Case then you can simply remove that parameter and use a query like:

Bson searchQuery = Filters.regex("name",search);

3.2. Search multiple words

If we have multiple words in search like:

String search = "ai in"

Then, we can split the words by space and start creating separate queries for each word then combine them all together and use them as a single query.

Example:

String[] searchTokens = search.split(" "); // Spliting words by space

Create a list of Bson object:

List<Bson> searchQueries = new ArrayList<>();

Create a separate query for each word in the search:

for(String token: searchTokens){
    searchQueries.add(Filters.regex("name",token, "i"));
}

Now, use searchQueries to find matched content:

userCollection.find(Filters.or(searchQueries)); 

This query will return all the names that have either ai or in or both in their name.

Complete example code:

String search = "ai in";
String[] searchTokens = search.split(" "); // Spliting words by space
List<Bson> searchQueries = new ArrayList<>();
for(String token: searchTokens){
    searchQueries.add(Filters.regex("name",token, "i"));
}
// The Filters.or(searchQueries) will generats an OR operator so that 
// It matches any words given in search criteria
userCollection.find(Filters.or(searchQueries)); 

4. Summary

In this post, we learned to implement a search in MongoDB using Java.

Sharing Is Caring:
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments