Skip to main content

Getting started with Spring Data MongoDB (Spring Boot + MongoDB)

Install and start mongodb

You can install MongoDB on a Mac using Homebrew, which is a popular package manager for macOS. Here are the steps to install MongoDB on a Mac using Homebrew:

1) Open the Terminal application on your Mac.

2) Install Homebrew by running the following command in the Terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

3) Once Homebrew is installed, run the following command to update the Homebrew package database:

brew update

4) You can add the custom tap in a MacOS terminal session using:

brew tap mongodb/brew

5) Finally, run the following command to install MongoDB:

brew install mongodb-community

6) Once the installation is complete, you can start MongoDB by running the following command:

mongod --config /usr/local/etc/mongod.conf

This will start the MongoDB server. You can now connect to MongoDB using the MongoDB shell or any MongoDB client.

7) Open a new Terminal window and start mongosh by running the following command:

mongosh

Spring Data MongoDB

Spring Data MongoDB is a module of the Spring Data project that provides a set of abstractions and utility classes for working with MongoDB databases in a Spring application.

It is built on top of the MongoDB Java driver and provides a high-level, Spring-style API for interacting with MongoDB databases.

1) Connect to MongoDB

To use Spring Data MongoDB, you need to include the following dependency in your build.gradle file:

To configure a Spring Data MongoDB application using the application.yml file, you will need to define the appropriate properties for your MongoDB database connection. Here is an example configuration:

2) CRUD Operations using MongoRepository

Spring Data MongoDB provides an easy ways to perform CRUD (Create, Read, Update, Delete) operations on MongoDB databases.


2.1) Model

In Spring Data MongoDB, the @Document annotation is used to specify the name of the MongoDB collection that a POJO class maps to.

The @Id annotation is used to specify the document ID field.

When you save an instance of the Impression class to the MongoDB database, it will be stored in the "impression" collection.

If you do not specify the collection name in the @Document annotation, Spring Data MongoDB will use the name of the POJO class with the first letter in lowercase as the collection name.

In MongoDB, a collection is a grouping of MongoDB documents. It is analogous to a table in a relational database.

A collection can store any type of MongoDB document, including JSON documents. Each document in a collection can have a different structure and set of fields, which makes MongoDB a flexible and schema-less database.

Collections are created automatically when the first document is inserted into them. They can also be explicitly created using the createCollection() method. Collections can be managed using the MongoDB shell or a MongoDB client.

2.2) Repository

The MongoRepository is an interface provided by Spring Data MongoDB that defines a set of CRUD methods for interacting with a MongoDB database.

It extends the PagingAndSortingRepository and CrudRepository interfaces, which provide additional methods for pagination and sorting, and basic CRUD operations, respectively.

MongoRepository also allows you to define custom query methods by simply declaring their method signature in the repository interface.

2.3) Controller

The @RestController annotation is used to define a class as a REST controller.

The @RequestMapping annotation is used to specify the base URL path for all methods in the class.

By default, Spring Boot will automatically serialize the response object to JSON format using the Jackson JSON library, so you can return any Java object from a REST controller method and it will be automatically converted to JSON.

2.4) SpringBootApplication

@SpringBootApplication is an annotation in Spring Boot that is used to mark a Java class as the main application class for a Spring Boot application.

It is a combination of three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan.

3) Operations using MongoTemplate

MongoTemplate is a core class in Spring Data MongoDB that provides a high-level API for interacting with MongoDB.

Testing

Swagger provides a web interface that allows you to interact with your API and test its endpoints.

Swagger UI

Source Code


Comments

Popular posts from this blog

Deploying Spring Boot microservices on Kubernetes Cluster

This article guides you through the deployment of two Spring Boot microservices, namely "order-service" and "inventory-service," on Kubernetes using "MiniKube" . We will establish communication between them, with "order-service" making calls to an endpoint in "inventory-service." Additionally, we will configure "order-service" to be accessible from the local machine's browser . 1) Create Spring Boot microservices The Spring Boot microservices, "order-service" and "inventory-service," have been developed and can be found in this GitHub repository. If you are interested in learning more about creating Spring Boot REST microservices, please refer to this or this (Reactive) link. 2) Build Docker Images The Docker images for both "order-service" and "inventory-service" have already been generated and deployed on DockerHub, as shown below. codeburps/order-service cod...

Circuit Breaker Pattern with Resilience4J in a Spring Boot Application

Read Also: Spring Cloud Circuit Breaker + Resilience4j Resilience4j is a lightweight fault tolerance library that draws inspiration from Netflix Hystrix but is specifically crafted for functional programming. The library offers higher-order functions, known as decorators , designed to augment any functional interface, lambda expression, or method reference with features such as Circuit Breaker, Rate Limiter, Retry, or Bulkhead . These functionalities can be seamlessly integrated within a project, class, or even applied to a single method. It's possible to layer multiple decorators on any functional interface, lambda expression, or method reference, allowing for versatile and customizable fault tolerance. While numerous annotation-based implementations exist online, this article focuses solely on the reactive approach using router predicates and router functions . How Circuit Breaker Pattern works? In general, a circuit breaker functions as an automatic electrical s...

How to create a basic Spring 6 project using Maven

Below is a step-by-step guide to creating a basic Spring project using Maven. 1) Create a Maven Project Use the following Maven command to create a new Maven project. mvn archetype:generate -DgroupId=com.tb -DartifactId=spring-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 2) Import in IntelliJ IDEA If you haven't already, open IntelliJ IDEA on your system. Go to "File" > "New" > "Project from Existing Sources..." . In the file dialog, navigate to the directory where your Maven project is located. Select the pom.xml file within the project directory and click "Open." 3) Update pom.xml In total, the application requires the below-mentioned dependencies: 4) Create Spring Configuration Create a Java configuration class that uses annotations to define your Spring beans and their dependencies. This class should be annotated with @Configuration . 5) Create the Main Application C...