You are here
Home > MongoDB >

Spring Boot MongoDB Query Examples

Spring Boot MongoDB @Query Examples, Spring Data MongoDB Queries, @Query Annotation in Spring Boot MongoDB, Spring Boot MongoDB Query Examples, Spring Data MongoDB Queries, @Query mongodb spring boot example, mongodb queries, spring mongodb, @query mongodb spring, @query in spring boot mongodb, spring boot mongodb query like, mongodb spring boot custom query

Spring Boot MongoDB @Query ExamplesIn previous article ‘Spring Boot MongoDB CRUD Example‘, we have already covered the ‘How to write CRUD operations using Spring Boot & MongoDB’. Further, in this article we will learn ‘How to develop queries using Spring Boot & MongoDB’. However, if we extend our custom Repository interface from MongoRepository<T, ID>, we can at least develop CRUD operations without adding any method in our custom Repository. But sometimes, we need complex data from MongoDB. In that case, we need to declare some methods in our Repository interface in order to get data from MongoDB. In this context, knowledge of query operations in MongoDB becomes mandatory to know. Hence, we will discuss about Spring Boot MongoDB Query Examples in this article.

We will learn by comparing MongoDB queries with SQL queries. In this way, we will understand it easily and also save a lot of time in learning. In the end, we will also look at queries using regular expressions similar to ‘LIKE’ statement of the SQL queries. Now, let’s discuss about our topic ‘Spring Boot MongoDB @Query Examples’.

Why to use @Query Annotation with Spring Boot & MongoDB?

We can use the @Query annotation to specify a custom query to declare a method of custom Repository. It works equally well with MongoDB as it does with JPA. However, the only difference is that in case of MongoDB, @Query takes a JSON query string instead of a JPA query. For example, @Query(“{id :?0}”) clearly indicates that the annotation is accepting JSON query string. We can check all Optional Element’s of @Query from the official website. Moreover, with this annotation, we can execute almost all the complex queries. It is also sometimes very handy in executing native MongoDB queries. We can even take advantage of MongoDB native operators and operations using this annotation.

Coding Steps to develop Spring Boot MongoDB Query Examples

In order to develop and test Query examples, we will first write codes and insert some records into DB. Thereafter, we will start testing Query Examples step by step.

Step#0 : Setup MongoDB with Spring Boot

Make sure you already have installed MongoDB in your system. If not, kindly visit ‘How to install MongoDB in your system ?‘. Here, you will also get some useful commands to work with MongoDB. In order to get hold on Spring Boot with MongoDB, kindly visit ‘How to work with MongoDB in Spring Boot?‘.

Step#1 : Create a Spring Boot Project using STS(Spring Tool Suite)

Here, we will use STS(Spring Tool Suite) to create our Spring Boot Project. If you are new to Spring Boot, visit Internal Link to create a sample project in spring boot using STS. While creating a project in STS, add starters ‘Spring Data MongoDB’, and ‘Lombok’ in order to get the features of MongoDB. Furthermore, if you are new to ‘Lombok’, kindly visit ‘How to configure Lombok‘ and to know all about it in detail.

Step#2 : Update application.properties

Update application.properties as below.

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=springBootMongoDB

If you are using MongoDB in authentication mode, include the username and password of it accordingly.

Step#3 : Create Entity class

Here we will use Book as an entity to illustrate the examples. Hence, create a Book.java class as below. However, we will consider the collection name as ‘Books’ in MongoDB. It is just to illustrate the use of element ‘collection’ in @Document annotation. Moreover, we are using ‘Lombok‘ in order to reduce the boilerplate code.

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "Books")
public class Book {

      @Id
      private Integer id;

      private String name;
      private Integer pages;
      private String author;
      private Double cost;
}

In this example, we have taken id as integer. If you are looking for an example where id as a String, kindly visit our previous tutorial on Spring Boot Mongo DB CRUD Example.

Step#4 : Create a Repository Interface

In order to support DB operations, we will create one Repository interface. As per convention, we should name the repository prefixed with Entity name. Hence, let’s name it as BookRepository.java. Moreover, it will extend MongoRepository<Book, Integer> interface in order to get the support of queries. For example, Let’s declare some methods using @query annotations as below. Mentioned comments will help us to understand the logic behind each method accordingly.

import org.springframework.data.mongodb.repository.MongoRepository;
import com.dev.springboot.mongodb.entity.Book;

public interface BookRepository extends MongoRepository<Book, Integer> {
     
 //--------------------------------custom query methods------------------------
          
          @Query("{id :?0}")                                                  //SQL Equivalent : SELECT * FROM BOOK WHERE ID=?
          Optional<Book> getBookById(Integer id);

          @Query("{pages : {$lt: ?0}}")                                 // SQL Equivalent : SELECT * FROM BOOK where pages<?
          //@Query("{ pages : { $gte: ?0 } }")                        // SQL Equivalent : SELECT * FROM BOOK where pages>=?
          //@Query("{ pages : ?0 }")                                      // SQL Equivalent : SELECT * FROM BOOK where pages=?
          List<Book> getBooksByPages(Integer pages);

          
          @Query("{author : ?0}")                                         // SQL Equivalent : SELECT * FROM BOOK where author = ?
          List<Book> getBooksByAuthor(String author);

         
         @Query("{author: ?0, cost: ?1}")                            // SQL Equivalent : SELECT * FROM BOOK where author = ? and cost=?
         //@Query("{$and :[{author: ?0},{cost: ?1}] }")
         List<Book> getBooksByAuthorAndCost(String author, Double cost);

         
         @Query("{$or :[{author: ?0},{name: ?1}]}")            //SQL Equivalent : select count(*) from book where author=? or name=?
         List<Book> getBooksByAuthorOrName(String author, String name);

        
         @Query(value ="{author: ?0}", count=true)           //SQL Equivalent : select count(*) from book where author=?
         Integer getBooksCountByAuthor(String author);

         //Sorting
         @Query(value = "{author:?0}", sort= "{name:1}") //ASC
         //@Query(value = "{author=?0}", sort= "{name:-1}") //DESC
         List<Book> getBooksByAuthorSortByName(String author);

  //------------------- @Query with Projection ---------------------------------------
         @Query(value= "{pages: ?0}", fields="{name:1, author:1}")   // only data of name & author properties will be displayed
         //@Query(value= "{pages: ?0}", fields="{name:1, author:1, cost:1, pages:1}") // will display all properties data
         List<Book> getBookNameAndAuthorByPages(Integer pages);

        
         @Query(value= "{author : ?0}")           // SQL Equivalent : SELECT * FROM BOOK select * from books where author=?
         List<Book> getAllBooksByAuthor(String author);

 //------------------MongoDB Regular Expressions--------------------------------------
        @Query("{ author : { $regex : ?0 } }")
         List<Book> getBooksByAuthorRegEx(String author);

}

♥ ‘?0’ indicates that the mentioned property should be equal to the zeroth parameter to the query method. Further, if there were more parameters, they could be referred to ?1, ?2, and so forth.

♥ fields attribute is used for projections, where 1 indicates include field, and 0 indicates to exclude the field.

Note : We will consider writing a Runner class to write and test each operation in further steps. However, we will write only one Runner class to demonstrate it accordingly. 

Step#4 : Saving some records into MongoDB

Let’s first save some records into MongoDB. Further, we will utilize them to test our queries. Please note that we are using List.of() method to save multiple records in DB. However, It will work on JDK9 and above versions. You can also use Arrays.asList() method to save records if you are using lower than JDK9 version.

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.dev.springboot.model.Book;
import com.dev.springboot.repo.BookRepository;

@Component
public class SaveBooksRunner implements CommandLineRunner {

        @Autowired
        private BookRepository bookRepo;

        @Override
        public void run(String... args) throws Exception {

        bookRepo.saveAll(List.of(
                      new Book(500, "Core Java", 200, "Kathy Sierra", 1065.5),
                      new Book(501, "JSP & Servlets", 350, "Kathy Sierra", 1749.0),
                      new Book(502, "Spring in Action", 480, "Craig Walls", 940.75),
                      new Book(503, "Pro Angular", 260, "Freeman", 1949.25),
                      new Book(504, "HTML CSS", 100, "Thomas Powell", 2317.09),
                      new Book(505, "Hibernate in Action", 180, "Gavin King", 889.25),
                      new Book(506, "Practical MongoDB", 180, "Shakuntala Gupta", 785.0),
                      new Book(507, "Pro Spring Boot", 850, "Felipe Gutierrez", 2167.99),
                      new Book(508, "Beginning jQuery", 180, "Franklin", 1500.00),
                      new Book(509, "Java Design Patterns", 114, "Devendra Singh", 919.99)

        ));

        System.out.println("------All records has been saved successfully-------");

        }
}

Output from MongoDB

In order to display all saved records in MongoDB console, execute below command. Further, for some other handy commands visit internal article.

> db.Books.find().pretty()

{
"_id" : 500,
"name" : "Core Java",
"pages" : 200,
"author" : "Kathy Sierra",
"cost" : 1065.5,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 501,
"name" : "JSP & Servlets",
"pages" : 350,
"author" : "Kathy Sierra",
"cost" : 1749,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 502,
"name" : "Spring in Action",
"pages" : 480,
"author" : "Craig Walls",
"cost" : 940.75,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 503,
"name" : "Pro Angular",
"pages" : 260,
"author" : " Freeman",
"cost" : 1949.25,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 504,
"name" : "HTML CSS",
"pages" : 100,
"author" : "Thomas Powell",
"cost" : 2317.09,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 505,
"name" : "Hibernate in Action",
"pages" : 180,
"author" : "Gavin King",
"cost" : 889.25,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 506,
"name" : "Practical MongoDB",
"pages" : 180,
"author" : "Shakuntala Gupta",
"cost" : 785,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 507,
"name" : "Pro Spring Boot",
"pages" : 850,
"author" : "Felipe Gutierrez",
"cost" : 2167.99,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 508,
"name" : "Beginning jQuery",
"pages" : 180,
"author" : "Franklin",
"cost" : 1500,
"_class" : "com.dev.springboot.model.Book"
}
{
"_id" : 509,
"name" : "Java Design Patterns",
"pages" : 114,
"author" : "Devendra Singh",
"cost" : 919.99,
"_class" : "com.dev.springboot.model.Book"
}

Spring Boot MongoDB @Query Examples

getBookById()  Example using Spring Boot & MongoDB

Optional<Book> opt = bookRepo.getBookById(504);
if(opt.isPresent()) {
         System.out.println(opt.get());
}
else {
        System.out.println("DATA NOT FOUND");
}

Output

Book(id=504, name=HTML CSS, pages=100, author=Thomas Powell, cost=2317.09)

getBooksByAuthor()  Example using Spring Boot & MongoDB

bookRepo.getBooksByAuthor("Kathy Sierra").forEach(System.out::println);

Output

Book(id=500, name=Core Java, pages=200, author=Kathy Sierra, cost=1065.5)
Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0)

getBooksByPages()  Example using Spring Boot & MongoDB

For this example, we have written a query method to display list of books less than some number of pages.

bookRepo.getBooksByPages(400).forEach(System.out::println);

Output

Book(id=500, name=Core Java, pages=200, author=Kathy Sierra, cost=1065.5)
Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0)
Book(id=503, name=Pro Angular, pages=260, author= Freeman, cost=1949.25)
Book(id=504, name=HTML CSS, pages=100, author=Thomas Powell, cost=2317.09)
Book(id=505, name=Hibernate in Action, pages=180, author=Gavin King, cost=889.25)
Book(id=506, name=Practical MongoDB, pages=180, author=Shakuntala Gupta, cost=785.0)
Book(id=508, name=Beginning jQuery, pages=180, author=Franklin, cost=1500.0)
Book(id=509, name=Java Design Patterns, pages=114, author=Devendra Singh, cost=919.99)

getBooksByAuthorAndCost()  Example using Spring Boot & MongoDB

bookRepo.getBooksByAuthorAndCost("Freeman",1949.25).forEach(System.out::println);

Output

Book(id=503, name=Pro Angular, pages=260, author=Freeman, cost=1949.25)

getBooksByAuthorOrName()  Example using Spring Boot & MongoDB

bookRepo.getBooksByAuthorOrName("Kathy Sierra"," ").forEach(System.out::println);

bookRepo.getBooksByAuthorOrName("Freeman","Spring in Action").forEach(System.out::println);

Output

Book(id=500, name=Core Java, pages=200, author=Kathy Sierra, cost=1065.5)
Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0)

Book(id=502, name=Spring in Action, pages=480, author=Craig Walls, cost=940.75)
Book(id=503, name=Pro Angular, pages=260, author=Freeman, cost=1949.25)

getBooksCountByAuthor()  Example using Spring Boot & MongoDB

Integer count = bookRepo.getBooksCountByAuthor("Kathy Sierra"); System.out.println(count);

Output

2

getBooksByAuthorSortByName()  Example using Spring Boot & MongoDB

bookRepo.getBooksByAuthorSortByName("Kathy Sierra").forEach(System.out::println);

Output

Book(id=500, name=Core Java, pages=200, author=Kathy Sierra, cost=1065.5)
Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0)

getBookNameAndAuthorByPages()  Example using Spring Boot & MongoDB

bookRepo.getBookNameAndAuthorByPages(180).forEach(System.out::println);

Output

Book(id=505, name=Hibernate in Action, pages=null, author=Gavin King, cost=null)
Book(id=506, name=Practical MongoDB, pages=null, author=Shakuntala Gupta, cost=null)
Book(id=508, name=Beginning jQuery, pages=null, author=Franklin, cost=null)

Note : Here in the above output, notice the values of pages & cost properties. They are null because we have not mentioned these properties while declaring query method of BookRepository. Furthermore, if you want to get data of all properties, check getBookNameAndAuthorByPages() method in BookRepository class and uncomment the commented query. Once you uncomment it, you will get non-null results.

getAllBooksByAuthor()  Example using Spring Boot & MongoDB

bookRepo.getAllBooksByAuthor("Kathy Sierra").forEach(System.out::println);

Output

Book(id=500, name=Core Java, pages=200, author=Kathy Sierra, cost=1065.5)
Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0)

MongoDB Regular Expressions

Like SQL Queries with Regular Expressions, we can also use regular expressions to create MongoDB queries. However, there are some differences in writing regular expressions in MongoDB. In order to understand the differences let’s have a look at below table.

 

MongoDB Regular Expressions

getAllBooksByAuthor() Regular Expression Example using Spring Boot & MongoDB

Example#1

bookRepo.getBooksByAuthorRegEx("^S").forEach(System.out::println);

Output

Book(id=506, name=Practical MongoDB, pages=180, author=Shakuntala Gupta, cost=785.0)

Example#2

bookRepo.getBooksByAuthorRegEx("man$").forEach(System.out::println);

Output

Book(id=503, name=Pro Angular, pages=260, author=Freeman, cost=1949.25)

Example#3

bookRepo.getBooksByAuthorRegEx("S").forEach(System.out::println);

Output

Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0)
Book(id=506, name=Practical MongoDB, pages=180, author=Shakuntala Gupta, cost=785.0)
Book(id=509, name=Java Design Patterns, pages=114, author=Devendra Singh, cost=919.99)

It’s all about ‘Spring Boot MongoDB Query Examples’ from our side. In addition, if you want to learn more on this topic, you may visit official documentation. Additionally, If you want to learn more on NoSQL databases and have a good understanding of them, kindly visit a separate article on ‘All About NoSQL Databases‘.

Links to Other tutorials on MongoDB with Spring Boot

Below are the links to learn MongoDB deeply with Spring Boot.

MongoDB Basics & How to work with Spring Boot 
Spring Boot MongoDB CRUD Examples
Spring Boot MongoDB using MongoTemplate Examples including CRUD 

FAQs

What are the benefits of using @Query in Spring Boot MongoDB?

@Query annotation allows for more flexibility and readability in defining custom queries, particularlly for complex queries that cannot be expressed using Spring Data MongoDB’s method naming conventions.

Are there any limitations to using @Query in Spring Boot MongoDB?

Although using @Query annotation provides great flexibility, but it may not be suitable for all scenarios, specifically when dealing with dynamic queries or complex mapping requirements.

Is there any performance impact of using @Query in Spring Boot MongoDB?

It may have a very slight performance impact as compared to using repository methods that rely on method naming conventions, as the query parsing and execution may involve additional overhead.

Leave a Reply


Top