Create Database
Create a database with the name is SpringDataMongoDBRepository. This database have a collection: Product collection.
/* Create SpringDataMongoDBRepository database */
use SpringDataMongoDBRepository
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
db.getCollection('product').insertOne({
"name" : "Mobile 1",
"price" : 45.0,
"quantity" : 4.0,
"status" : true,
"date" : ISODate("2016-10-20T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"red",
"green",
"blue"
]
});
db.getCollection('product').insertOne({
"name" : "Mobile 2",
"price" : 12.0,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-11-14T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 2"
},
"colors" : [
"yellow",
"green"
]
});
db.getCollection('product').insertOne({
"name" : "Mobile 3",
"price" : 28.0,
"quantity" : 8.0,
"status" : true,
"date" : ISODate("2017-11-20T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 3"
},
"colors" : [
"black",
"blue"
]
});
db.getCollection('product').insertOne({
"name" : "Laptop 1",
"price" : 39.0,
"quantity" : 12.0,
"status" : false,
"date" : ISODate("2017-12-26T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711669"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue"
]
});
db.getCollection('product').insertOne({
"name" : "Laptop 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : true,
"date" : ISODate("2017-03-11T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711669"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue",
"yellow"
]
});
db.getCollection('product').insertOne({
"name" : "Tivi 1",
"price" : 22.0,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-06-26T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa4571166a"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue",
"white",
"black"
]
});
db.getCollection('product').insertOne({
"name" : "Tivi 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : false,
"date" : ISODate("2017-09-24T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa4571166a"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 3"
},
"colors" : [
"red",
"green"
]
});
Create Spring Boot Project
On the Spring Tool Suite, create a Spring Boot project
Enter Project Information:
- Name: SpringBootMongoDB
- Group: com.example.demo
- Artifact: SpringBootMongoDB
- Description: Learn Spring Boot MongoDB with Real Apps
- Package: com.example.demo
Select the technologies and libraries to be used:
- Spring Data MongoDB
- Spring Boot Devtools
Click Next button to show Project’s Information
Click Finish button to finish create Spring Boot project
Configure pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringBootMongoDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootMongoDB</name>
<description>Learn Spring Boot MongoDB with Real Apps</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Database Configuration
Open application.properties file in src/main/resources folder and add configurations connect to database as below:
spring.data.mongodb.database=SpringDataMongoDBRepository
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
Entities Class
Create new package named com.example.demo.entities. In this package, create new Java classes as below:
Brand Class
In com.example.demo.entities package, create new class named Brand.java as below:
package com.example.demo.entities;
public class Brand {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Brand(String id, String name) {
this.id = id;
this.name = name;
}
public Brand() {
}
}
Product Class
In com.example.demo.entities package, create new class named Product.java as below:
package com.example.demo.entities;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "product")
public class Product {
@Id
private String id;
private String name;
private double price;
private int quantity;
private boolean status;
private Date date;
private String categoryId;
private Brand brand;
private List<String> colors;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public Brand getBrand() {
return brand;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
public List<String> getColors() {
return colors;
}
public void setColors(List<String> colors) {
this.colors = colors;
}
}
ProductGroupBy Class
In com.example.demo.entities package, create new class named ProductGroupBy.java as below:
package com.example.demo.models;
import org.springframework.data.annotation.Id;
public class ProductGroupBy {
@Id
private String categoryId;
private long countProduct;
private double minPrice;
private double maxPrice;
private double avgPrice;
private long sumQuantities;
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public long getCountProduct() {
return countProduct;
}
public void setCountProduct(long countProduct) {
this.countProduct = countProduct;
}
public double getMinPrice() {
return minPrice;
}
public void setMinPrice(double minPrice) {
this.minPrice = minPrice;
}
public double getMaxPrice() {
return maxPrice;
}
public void setMaxPrice(double maxPrice) {
this.maxPrice = maxPrice;
}
public double getAvgPrice() {
return avgPrice;
}
public void setAvgPrice(double avgPrice) {
this.avgPrice = avgPrice;
}
public long getSumQuantities() {
return sumQuantities;
}
public void setSumQuantities(long sumQuantities) {
this.sumQuantities = sumQuantities;
}
}
ProductRepository Interface
Create new package named com.example.demo.repositories. In this package, create new interface named ProductRepository.java implement from CrudRepository interface of Spring Framework as below:
package com.example.demo.repositories;
import java.util.List;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.entities.Product;
import com.example.demo.entities.ProductGroupBy;
@Repository("productRepository")
public interface ProductRepository extends CrudRepository<Product, String> {
@Aggregation(pipeline = {
"{$group: {"
+ "_id: $categoryId, "
+ "countProduct: {$sum: 1},"
+ "minPrice: {$min: $price},"
+ "maxPrice: {$max: $price},"
+ "avgPrice: {$avg: $price},"
+ "sumQuantities: {$sum: $quantity}"
+ "}}"
})
public List<ProductGroupBy> groupBy();
}
ProductService Interface
Create new package named com.example.demo.services. In this package create new interface named ProductService.java as below:
package com.example.demo.services;
import java.util.List;
import com.example.demo.entities.ProductGroupBy;
public interface ProductService {
public List<ProductGroupBy> groupBy();
}
ProductServiceImpl Class
In com.example.demo.services package, create new java class named ProductServiceImpl.java implement from ProductService interface
package com.example.demo.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.entities.ProductGroupBy;
import com.example.demo.repositories.ProductRepository;
@Service("productService")
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductRepository productRepository;
@Override
public List<ProductGroupBy> groupBy() {
return productRepository.groupBy();
}
}
Configuration Class
Create new package named com.example.demo.configurations, create new Java class named MongoDBConfigurations.java as below:
package com.example.demo.configurations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.example.demo.services.ProductService;
import com.example.demo.services.ProductServiceImpl;
@Configuration
@EnableTransactionManagement
@EnableMongoRepositories(basePackages = { "com.example.demo.repositories" })
@ComponentScan("com.example.demo")
@PropertySource("classpath:application.properties")
public class MongoDBConfigurations {
@Autowired
private MongoDatabaseFactory mongoDatabaseFactory;
@Autowired
private MongoMappingContext mongoMappingContext;
@Bean
public MappingMongoConverter mappingMongoConverter() {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
@Bean
public ProductService productService() {
return new ProductServiceImpl();
}
}
Run Application
Create new package named com.example.demo.demo, create new Java class named Demo.java as below:
package com.example.demo.main;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import com.example.demo.configurations.MongoDBConfigurations;
import com.example.demo.entities.ProductGroupBy;
import com.example.demo.services.ProductService;
public class Demo {
public static void main(String[] args) {
try {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(MongoDBConfigurations.class);
ProductService productService = context.getBean(ProductService.class);
for (ProductGroupBy productGroupBy : productService.groupBy()) {
System.out.println("Category Id: " + productGroupBy.getCategoryId());
System.out.println("Min Price: " + productGroupBy.getMinPrice());
System.out.println("Max Price: " + productGroupBy.getMaxPrice());
System.out.println("Sum Quantities: " + productGroupBy.getSumQuantities());
System.out.println("Avg Price: " + productGroupBy.getAvgPrice());
System.out.println("Count Product: " + productGroupBy.getCountProduct());
System.out.println("=========================");
}
context.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Project Structure
Output
Category Id: 5a30de130867edfa4571166a
Min Price: 86.0
Max Price: 86.0
Sum Quantities: 23
Avg Price: 86.0
Count Product: 1
=========================
Category Id: 5a30de130867edfa45711669
Min Price: 39.0
Max Price: 86.0
Sum Quantities: 35
Avg Price: 62.5
Count Product: 2
=========================
Category Id: 5a30de130867edfa4571166a
Min Price: 90
Max Price: 90
Sum Quantities: 7
Avg Price: 90.0
Count Product: 1
=========================
Category Id: 5a30de130867edfa45711668
Min Price: 12.0
Max Price: 45.0
Sum Quantities: 19
Avg Price: 28.333333333333332
Count Product: 3
=========================