CODE WITH SIBIN

Solving Real Problems with Real Code


Spring Data MongoDB Annotations Guide with Examples

📁 Entity/Model Annotations

@Document

Declares a class as a MongoDB document. You can specify a collection name.

@Document(collection = "users")
public class User {
    // fields and methods
}

@Id

Marks the field used as the unique identifier (_id).

@Id
private String id;

@Field

Maps a Java field to a MongoDB document field (if names differ).

@Field("user_name")
private String username;

@Transient

Excludes the field from persistence (not stored in MongoDB).

@Transient
private String temporaryData;

@DBRef

Declares a relationship to another MongoDB document (like a reference/foreign key).

@DBRef
private Address address;

@Indexed

Declares an index on a single field.

@Indexed(unique = true)
private String email;

@TextIndexed

Enables full-text search capabilities by indexing this field.

@TextIndexed
private String description;

@GeoSpatialIndexed

Adds a geospatial index for location-based queries.

@GeoSpatialIndexed
private double[] location;

@CompoundIndex

Defines a compound index on a document.

@CompoundIndex(name = "user_compound_idx", def = "{'firstName': 1, 'lastName': 1}")
public class User {
    // fields
}

📚 Repository/Query Annotations

@Query

Custom MongoDB query using JSON syntax.

public interface UserRepository extends MongoRepository<User, String> {
    @Query("{'email': ?0}")
    User findByEmail(String email);
    
    @Query(value = "{'age': {$gt: ?0}}", fields = "{'name': 1}")
    List<User> findUsersOlderThan(int age);
}

@Aggregation

Allows you to define MongoDB aggregation pipelines in repository methods.

public interface UserRepository extends MongoRepository<User, String> {
    @Aggregation(pipeline = {
        "{'$match': {'age': {$gt: ?0}}}",
        "{'$group': { '_id': '$department', 'count': { '$sum': 1 }}}"
    })
    List<DepartmentCount> groupByDepartment(int minAge);
}

@Meta

Sets metadata such as sorting and max execution time for a query.

@Meta(flags = {CursorOption.NO_TIMEOUT}, maxExecutionTimeMs = 5000)
List<User> findByLastName(String lastName);

⚙️ Configuration & Enabling Annotations

@EnableMongoRepositories

Enables scanning of repository interfaces for MongoDB.

@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MongoConfig {
    // configuration
}

@EnableReactiveMongoRepositories

Enables reactive Mongo repositories.

@Configuration
@EnableReactiveMongoRepositories
public class ReactiveMongoConfig {
    // configuration
}

Complete Example Program

// Entity
@Document(collection = "employees")
@CompoundIndex(name = "name_department_idx", def = "{'firstName': 1, 'department': 1}")
public class Employee {
    @Id
    private String id;
    
    @Field("first_name")
    private String firstName;
    
    @Indexed(unique = true)
    private String email;
    
    @TextIndexed
    private String bio;
    
    @DBRef
    private Department department;
    
    @Transient
    private String temporaryNote;
    
    // constructors, getters, setters
}

// Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {
    @Query("{'email': ?0}")
    Employee findByEmailAddress(String email);
    
    @Query(value = "{'department.name': ?0}", fields = "{'firstName': 1, 'email': 1}")
    List<Employee> findByDepartmentName(String departmentName);
    
    @Aggregation(pipeline = {
        "{'$match': {'active': true}}",
        "{'$group': {'_id': '$department', 'count': {'$sum': 1}}}"
    })
    List<DepartmentCount> countActiveEmployeesByDepartment();
}

// Main Application
@SpringBootApplication
@EnableMongoRepositories
public class MongoDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MongoDemoApplication.class, args);
    }
}

Key Points to Remember

  1. Entity Mapping: Use @Document for your MongoDB entities and @Id for the identifier field.
  2. Field Customization:
    • Use @Field when your Java field name differs from MongoDB field name
    • Use @Transient to exclude fields from persistence
  3. Indexing:
    • Single field indexes with @Indexed
    • Compound indexes with @CompoundIndex
    • Special indexes like @TextIndexed and @GeoSpatialIndexed
  4. Relationships: Use @DBRef for document references (though MongoDB is document-oriented and doesn't have joins like SQL)
  5. Querying:
    • Custom queries with @Query
    • Complex operations with @Aggregation
    • Query metadata with @Meta
  6. Configuration:
    • Enable repositories with @EnableMongoRepositories
    • Use reactive variant for reactive programming

These annotations provide powerful tools for working with MongoDB in Spring applications while maintaining clean, declarative code.

Leave a Reply

Your email address will not be published. Required fields are marked *