Spring Data MongoDB
Not all data fits in rows and columns. MongoDB stores data the way your app thinks about it.
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).
- @Document: The NoSQL equivalent of
@Entity. Maps a Java class to a MongoDB collection (table). - MongoRepository: The NoSQL equivalent of
JpaRepository. Providessave(),findById(), etc. - No Schema: You don’t need
ddl-autoor Flyway. MongoDB creates the collection automatically when you save the first document.
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/devinhyderabadThe 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(); }
}The code above demonstrates:
- @Document: Maps the Java class to a MongoDB collection named “products”. Note the imports use
org.springframework.data.annotation.Id, NOTjakarta.persistence.Id. - MongoRepository: Works exactly like
JpaRepository. You get CRUD methods for free. The generic parameters areMongoRepository<Product, String>because MongoDB uses String IDs by default. - Flexibility: You can add new fields to
Productwithout breaking old documents in the database. Old documents will just havenullfor the new field.
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
Want to track your progress?
Log in to save your place and pick up where you left off.
Progress track karna chahte ho?
Login karo apni progress save karne ke liye aur jahan chhoda tha wahan se shuru karo.
Login