Spring Boot & MongoDB integration

A Spring Boot REST API that connects to MongoDB, performs CRUD operations, and uses Spring Data MongoDB.


🧱 1. Maven Dependencies

<!-- Spring Boot Starter for MongoDB -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<!-- Optional: Spring Web for REST APIs -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>


⚙️ 2. application.properties

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

💡 You can also use spring.data.mongodb.uri=mongodb://localhost:27017/demo_db


📦 3. Model Class (Document)

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "products")
public class Product {
    @Id
    private String id;
    private String name;
    private double price;

    // Constructors, Getters, Setters
}


🧠 4. Repository Interface

import org.springframework.data.mongodb.repository.MongoRepository;

public interface ProductRepository extends MongoRepository<Product, String> {
    List<Product> findByName(String name);
}


🌐 5. REST Controller (CRUD)

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @Autowired
    private ProductRepository repository;

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return repository.save(product);
    }

    @GetMapping
    public List<Product> getAllProducts() {
        return repository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable String id) {
        return repository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable String id, @RequestBody Product updated) {
        return repository.findById(id)
                .map(product -> {
                    product.setName(updated.getName());
                    product.setPrice(updated.getPrice());
                    return ResponseEntity.ok(repository.save(product));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable String id) {
        repository.deleteById(id);
    }
}


🧪 6. Testing the API

Use Postman or curl:

Create:

POST /api/products
{
  "name": "Pen",
  "price": 20.5
}

Get All:

GET /api/products

✅ Summary

Component Purpose
@Document Maps Java class to MongoDB collection
MongoRepository Provides built-in CRUD methods
MongoDB Config Handled automatically via application.properties
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.