Spring Boot MongoDB CRUD Example with Image Upload
In this tutorial, you will build a complete Spring Boot + MongoDB CRUD application with image upload support. Students can be added, updated, deleted, and retrieved via REST APIs, and profile images are stored directly in MongoDB as Binary BSON type.
You will learn how to install MongoDB, configure Spring Data MongoDB, use
MongoRepository, and store MultipartFile bytes in a MongoDB
document.
Download MongoDB
Download the MongoDB Community Edition from the official website:
Install and Open MongoDB
After downloading, install MongoDB and open MongoDB Compass (the GUI tool bundled with it):
Create Database and Collection
Click Connect → Create Database → enter the database and collection name:
Verify Database Creation
Your database and collection are now successfully created:
Project Structure
The Spring Boot project follows a clean layered package structure:
SpringBootMongoDbApplication.java
Standard Spring Boot entry point.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootMongoDbApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMongoDbApplication.class, args);
}
}
ImageController.java
Handles image upload. The uploaded MultipartFile is converted to a
Binary BSON object and saved to the images collection.
package com.example.demo.controller;
import java.io.IOException;
import org.bson.BsonBinarySubType;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.model.ProfileImage;
import com.example.demo.repository.ImageRepo;
@RestController
public class ImageController {
@Autowired
private ImageRepo imageRepo;
@PostMapping("/image")
public ProfileImage imageUpload(@RequestParam("image") MultipartFile file)
throws IOException {
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
ProfileImage profileImage = new ProfileImage();
profileImage.setImage(new Binary(BsonBinarySubType.BINARY, file.getBytes()));
return imageRepo.insert(profileImage);
}
}
StudentController.java
REST endpoints for CRUD operations on Student documents.
package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/addStudent")
public Student addStudentPage(@RequestBody Student student)
throws Exception {
return studentService.addStudentPage(student);
}
@DeleteMapping("/delete/{id}")
public String deleteStudent(@PathVariable String id) throws Exception {
return studentService.deleteStudent(id);
}
@PutMapping("/update/{id}")
public Student updateStudent(@PathVariable String id,
@RequestBody Student student) throws Exception {
return studentService.updateStudent(id, student);
}
@GetMapping("/students")
public List<Student> getAllStudents() {
return studentService.getAllStudents();
}
@GetMapping("/student/{id}")
public Student getStudent(@PathVariable String id) throws Exception {
return studentService.getStudent(id);
}
}
ProfileImage.java
The ProfileImage document stores an image as a BSON
Binary field. This supports up to 16 MB per document.
package com.example.demo.model;
import org.bson.types.Binary;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "images")
public class ProfileImage {
@Id
private String id;
private Binary image;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
}
Student.java
The Student document stores basic student fields plus an optional profile
image as Binary.
package com.example.demo.model;
import org.bson.types.Binary;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "student")
public class Student {
@Id
private String id;
private String name;
private float marks;
private Binary image;
public Binary getImage() {
return image;
}
public void setImage(Binary image) {
this.image = image;
}
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 float getMarks() {
return marks;
}
public void setMarks(float marks) {
this.marks = marks;
}
}
ImageRepo.java & StudentRepository.java
ImageRepo.java
package com.example.demo.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.ProfileImage;
@Repository
public interface ImageRepo extends MongoRepository<ProfileImage, String> {
}
StudentRepository.java
package com.example.demo.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Student;
@Repository
public interface StudentRepository extends MongoRepository<Student, String> {
}
Note: MongoRepository automatically provides
save(), findById(), findAll(),
delete(), and insert() methods — no implementation needed.
StudentService.java
Service layer wraps repository calls with business logic — including proper
Exception handling when a student ID is not found.
package com.example.demo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public Student addStudentPage(Student student) {
return studentRepository.save(student);
}
public String deleteStudent(String id) throws Exception {
Student dbstudent = studentRepository.findById(id)
.orElseThrow(() -> new Exception("This Student id is not found : " + id));
studentRepository.delete(dbstudent);
return "delete successfully";
}
public Student updateStudent(String id, Student student) throws Exception {
Student dbstudent = studentRepository.findById(id)
.orElseThrow(() -> new Exception("This Student id is not found : " + id));
dbstudent.setMarks(student.getMarks());
dbstudent.setName(student.getName());
return studentRepository.save(dbstudent);
}
public List<Student> getAllStudents() {
return studentRepository.findAll();
}
public Student getStudent(String id) throws Exception {
Student student = studentRepository.findById(id)
.orElseThrow(() -> new Exception("This Student id is not found : " + id));
return student;
}
}
application.properties
server.port=9898
spring.data.mongodb.uri=mongodb://localhost:27017/collegedb
spring.servlet.multipart.max-file-size=256MB
spring.servlet.multipart.max-request-size=256MB
spring.servlet.multipart.enabled=true
Key settings:
spring.data.mongodb.uri— points to the local MongoDB instance and thecollegedbdatabase.spring.servlet.multipart.max-file-size— increases the default 1 MB upload limit to 256 MB.
pom.xml Dependencies
Add the following dependencies to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
spring-boot-starter-data-mongodb brings in the MongoDB Java driver and
Spring Data MongoDB. spring-boot-starter-web provides the REST and
MultipartFile support.
Output Screens
Below are the output screenshots of the running application:
How It Works (Step-by-Step)
-
Configure MongoDB URI —
application.propertiesconnects Spring Boot to the local MongoDB instance and thecollegedbdatabase. -
Auto-configure MongoRepository — Spring Data MongoDB scans
@Documentclasses and generates implementations for repositories extendingMongoRepository. -
Upload an image —
POST /imageaccepts aMultipartFile, converts the bytes tonew Binary(BsonBinarySubType.BINARY, ...), and saves it. -
Add a student —
POST /addStudentwith JSON body saves aStudentdocument._idis auto-generated. -
Fetch students —
GET /studentsreturns all documents;GET /student/{id}returns one by ID. -
Update a student —
PUT /update/{id}looks up the existing document and updates only the fields provided. -
Delete a student —
DELETE /delete/{id}removes the document and returns a confirmation message.
Alternative for large files: If you need to store files larger than 16 MB, use GridFS instead of Binary. GridFS splits the file into chunks across multiple documents. Spring Data MongoDB provides GridFsTemplate for this.
Frequently Asked Questions
How do I connect Spring Boot to MongoDB?
Add the spring-boot-starter-data-mongodb dependency and set
spring.data.mongodb.uri in application.properties. Spring Boot
auto-configures a MongoTemplate and enables MongoRepository
interfaces automatically.
How do I store images in MongoDB using Spring Boot?
Use org.bson.types.Binary to store image bytes in a document field. Read
MultipartFile bytes and wrap them in
new Binary(BsonBinarySubType.BINARY, file.getBytes()). Save the entity via
MongoRepository. For large files (>16 MB), use GridFS instead.
What is the difference between MongoRepository and MongoTemplate?
MongoRepository provides Spring Data-style CRUD methods
(save, findById, findAll,
deleteById) with no boilerplate. MongoTemplate provides
fine-grained control over queries, updates, and aggregations. Use
MongoRepository for simple CRUD and MongoTemplate for complex
queries.
Can MongoDB store images directly in a document?
Yes, MongoDB supports Binary BSON type which can hold up to 16 MB per
document. For larger files, MongoDB provides GridFS, which splits files
into chunks across multiple documents.
How do I handle file upload size limits in Spring Boot?
Set spring.servlet.multipart.max-file-size and
spring.servlet.multipart.max-request-size in
application.properties. Example:
spring.servlet.multipart.max-file-size=256MB. Without this, Spring Boot
defaults to 1 MB per file.
Conclusion
In this tutorial, you built a complete Spring Boot + MongoDB CRUD
application with image upload support. You learned how to install MongoDB,
configure Spring Data MongoDB, use MongoRepository, and store image bytes
as BSON Binary.
You can extend this project with pagination, sorting, custom queries using
@Query, image retrieval endpoints, or switch to GridFS for
large file storage.
Related topics: Spring Data MongoDB Aggregations, GridFS with Spring Boot, MongoTemplate Queries, MongoDB Indexing, Spring Boot REST API Best Practices
No comments:
Post a Comment