Spring Boot Data MongoDB

📌 Common Spring Data MongoDB Annotations

  1. @Document
    • Marks a class as a MongoDB document (like an @Entity in JPA).
    • collection attribute can specify the collection name.
    @Document(collection = "users") public class User { ... }
  2. @Id
    • Marks the primary identifier field (usually _id in MongoDB).
    @Id private String id;
  3. @Field
    • Maps a Java field to a specific MongoDB field name.
    @Field("user_name") private String name;
  4. @Transient
    • Excludes a field from being persisted to MongoDB.
    @Transient private int tempValue;
  5. @Indexed / @CompoundIndex / @TextIndexed
    • Creates indexes for query optimization.
    @Indexed(unique = true) private String email; @TextIndexed private String description; @CompoundIndex(name = "name_age_idx", def = "{'name': 1, 'age': -1}")
  6. @DBRef
    • Creates a relationship (reference) to another document.
    @DBRef private List<Role> roles;
  7. @CreatedDate / @LastModifiedDate
    • For auditing — automatically sets created and modified timestamps.
    @CreatedDate private LocalDateTime createdAt; @LastModifiedDate private LocalDateTime updatedAt;

📌 Example: Spring Boot + MongoDB

1. Dependency (pom.xml)

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

2. Document Class

import org.springframework.data.annotation.*;
import org.springframework.data.mongodb.core.mapping.*;

import java.time.LocalDateTime;
import java.util.List;

@Document(collection = "users")
public class User {

    @Id
    private String id;

    @Field("user_name")
    private String name;

    @Indexed(unique = true)
    private String email;

    @DBRef
    private List<Role> roles;

    @CreatedDate
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime updatedAt;

    @Transient
    private int tempValue; // not stored in DB

    // getters & setters
}

3. Repository

import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.Optional;

public interface UserRepository extends MongoRepository<User, String> {
    Optional<User> findByEmail(String email);
}

4. Service

import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {

    private final UserRepository repo;

    public UserService(UserRepository repo) {
        this.repo = repo;
    }

    public User saveUser(User user) {
        return repo.save(user);
    }

    public List<User> getAllUsers() {
        return repo.findAll();
    }
}

5. Controller

import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService service;

    public UserController(UserService service) {
        this.service = service;
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return service.saveUser(user);
    }

    @GetMapping
    public List<User> getUsers() {
        return service.getAllUsers();
    }
}

âš¡ With this setup:

  • @Document makes User a MongoDB document.
  • @Id, @Field, @Indexed, @DBRef, @CreatedDate, @LastModifiedDate, and @Transient show how annotations work in practice.

Leave a Reply