Chapter 8.2☕ 16 min read

Spring Data MongoDB

Not all data fits in rows and columns. MongoDB stores data the way your app thinks about it.

01The Concept: Document Database

The Hyderabad Laad Bazaar Bangle Store Analogy:

In a traditional SQL table (like an Excel sheet), every bangle must have the exact same columns: Color, Size, Price. If you get a new bangle with a “Glitter” feature, you have to alter the whole table to add a “Glitter” column.

In MongoDB, it’s like a set of loose folders. Folder 1 can have {color, size}. Folder 2 can have {color, size, glitter, battery}. The structure is flexible. MongoDB stores these as BSON documents (Binary JSON).

02Technical Explanation
  1. @Document: The NoSQL equivalent of @Entity. Maps a Java class to a MongoDB collection (table).
  2. MongoRepository: The NoSQL equivalent of JpaRepository. Provides save(), findById(), etc.
  3. No Schema: You don’t need ddl-auto or Flyway. MongoDB creates the collection automatically when you save the first document.
03Full Working Code: MongoDB Integration

Add the MongoDB dependency to pom.xml. (Run MongoDB locally via Docker: docker run -p 27017:27017 mongo).

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

application.properties

spring.data.mongodb.uri=mongodb://localhost:27017/devinhyderabad

The Code (Product.java and ProductController.java)

package com.devinhyderabad;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.web.bind.annotation.*;
import java.util.List;

// 1. Maps to a MongoDB collection named "products"
@Document(collection = "products")
public class Product {
@Id
private String id; // Mongo uses String IDs by default
private String name;
private double price;

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; }
}

// 2. Repository interface (Exactly like JPA)
interface ProductRepository extends MongoRepository<Product, String> {}

@RestController
@RequestMapping("/api/products")
class ProductController {
private final ProductRepository repo;
public ProductController(ProductRepository repo) { this.repo = repo; }

@PostMapping
public Product create(@RequestBody Product p) { return repo.save(p); }

@GetMapping
public List<Product> getAll() { return repo.findAll(); }
}
04Code Walkthrough

The code above demonstrates:

  • @Document: Maps the Java class to a MongoDB collection named “products”. Note the imports use org.springframework.data.annotation.Id, NOT jakarta.persistence.Id.
  • MongoRepository: Works exactly like JpaRepository. You get CRUD methods for free. The generic parameters are MongoRepository<Product, String> because MongoDB uses String IDs by default.
  • Flexibility: You can add new fields to Product without breaking old documents in the database. Old documents will just have null for the new field.
05Why It Matters / Interview Note

Interview Question: “When would you choose MongoDB over a traditional SQL database like PostgreSQL?”

Answer: I would use MongoDB for highly unstructured or semi-structured data that changes frequently, like product catalogs, IoT sensor logs, or user preferences. I would use SQL when data integrity, strict ACID transactions, and complex JOINs across multiple tables are the primary requirement (e.g., banking systems).

Enterprise Note: MongoDB supports ACID transactions starting from version 4.0, meaning you can use it for financial data now. However, it is still slower for multi-table joins compared to SQL, so choosing the right DB based on the data shape is critical.

Key Takeaways

  • ✅ MongoDB is schema-less: documents in the same collection can have different fields
  • ✅ @Document maps a Java class to a MongoDB collection (@Entity equivalent)
  • ✅ MongoRepository provides CRUD just like JpaRepository
  • ✅ MongoDB uses String IDs by default (ObjectId)
  • ✅ Choose MongoDB for flexible data; choose SQL for strict relational integrity