SpringPortal #4 - Querying MongoDB with Spring Boot
Published: 2022-11-27 17:22:35

---
title: SpringPortal #4 - Querying MongoDB with Spring Boot
published: true
date: 2022-11-17 20:16:43 UTC
tags: 
canonical_url: https://24naman.hashnode.dev/springportal-4-querying-mongodb-with-spring-boot
---

## Loading Sample data in MongoDB Atlas

A task of an API that allows us to interact with a database. In the earlier [article](https://dev.to/24naman/springportal-3-mongodb-atlas-with-spring-boot-bom-temp-slug-8754353), we discussed how to interact with MongoDB in the Spring framework by adding and querying the data by the ID.

But sometimes we'll require more than just a simple query with the ID. Spring allows us to define a query by writing a method in an interface that extends [MongoRepository](https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/repository/MongoRepository.html).

In this article, we'll go through the various ways to write these functions to convey our query to the Spring framework. Also, what to do when writing these function definitions is not enough.

We'll use `sample_airbnb.listingsAndReviews` collection which is available in the [MongoDB sample database](https://www.mongodb.com/docs/atlas/sample-data/)

## Setting up the Application

1. Create a new Spring Application

2. Document Class

3. Repository Interface for the application

## Querying from MongoRepository

- Spring allows creating functions in MongoRepository which is similar to the following pattern:

- This helps run simple queries in MongoRepository by defining them as function names.

- But if the query becomes too complex (if the query uses several `and` & `or` clauses) then it is better to use an alternative method as the function names become hard to read and manage.

- Spring provides `@Query` annotation which makes it easy to declare queries in the repository.

- `@Query` allows writing native JSON-like queries from MongoDB in the Spring application.
- This annotation is at the method level, so we can define a method under any name and annotate it with `@Query` to run our native queries.
  - To use function params in the `@Query` annotation, params in Spring queries are marked as `?0`, `?1`, etc. and Spring passes the corresponding from the function definition to the `@Query`.

## MongoRepository Queries

In the following examples, each query is defined in two ways:

```
1. Defined in the function name
2. Defined with ```@Query``` annotation.

```

1. Find by 1 field

2. Find by 2 fields

3. Find by - not equal to 1 field

4. Find by 1 field and sort by field[s]

5. Find by value which exists between two values

6. Find by Regular expression

## Pageable?

- Pageable class allows us to handle a large subset of the dataset.
- It helps in navigating the data in a paginated manner.
- Page numbers start from 0 and each page size (number of records on one page) is user-defined.
- A pageable request is created using `PageRequest` class.
- `PageRequest` have 4 static methods to create a request for Pageable: 
  1. `PageRequest of(int page, int size)`
  2. `PageRequest of(int page, int size, Sort sort)`
  3. `PageRequest of(int page, int size, Direction direction, String... properties)`
  4. `PageRequest ofSize(int pageSize)` - first (0-th) page with specified size.
- `Direction` is an Enum with two values - `ASC` & `DESC`.

* * *

## GitLab

[Code Repository](https://gitlab.com/spring-hashnode/hello-spring-mongodb)

[Article-specific commit](https://gitlab.com/spring-hashnode/hello-spring-mongodb/-/commit/e7e6bf636ca23070c9c8c8f0bad183ac2ea7ccea)

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2104033689576056"
     crossorigin="anonymous"></script>