Skip to content

Instantly share code, notes, and snippets.

@kavicastelo
Created April 23, 2025 17:48
Show Gist options
  • Select an option

  • Save kavicastelo/234e14d7254df363acb3101bce5a4f6a to your computer and use it in GitHub Desktop.

Select an option

Save kavicastelo/234e14d7254df363acb3101bce5a4f6a to your computer and use it in GitHub Desktop.
MongoDB Learning Module 2 (Interns) – MongoDB Integration with Spring Boot
# For MongoDB Atlas (change accordingly)
spring.data.mongodb.uri=mongodb://localhost:27017/companyDB
# OR use MongoDB Atlas URI like:
# spring.data.mongodb.uri=mongodb+srv://<user>:<pass>@cluster.mongodb.net/companyDB
@Document("employees")
public class Employee {
@Id
private String id;
@NotBlank
private String name;
private String department;
private int age;
private List<String> skills;
// Getters, setters, constructors
}
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@Autowired
private EmployeeRepository repository;
@PostMapping
public Employee create(@RequestBody Employee e) {
return repository.save(e);
}
@GetMapping
public List<Employee> all() {
return repository.findAll();
}
@GetMapping("/search/department/{dept}")
public List<Employee> byDept(@PathVariable String dept) {
return repository.findByDepartment(dept);
}
@GetMapping("/search/age/{age}")
public List<Employee> byAge(@PathVariable int age) {
return repository.findByAgeGreaterThan(age);
}
@GetMapping("/search/skills/{skill}")
public List<Employee> bySkill(@PathVariable String skill) {
return repository.findBySkillsContaining(skill);
}
}
public interface EmployeeRepository extends MongoRepository<Employee, String> {
List<Employee> findByDepartment(String department);
List<Employee> findByAgeGreaterThan(int age);
List<Employee> findBySkillsContaining(String skill);
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
springboot-mongodb-module/
├── src/
│   └── main/
│       ├── java/
│       │   └── com.example.mongodbmodule/
│       │       ├── model/Employee.java
│       │       ├── repository/EmployeeRepository.java
│       │       └── controller/EmployeeController.java
│       └── resources/
│           └── application.properties
├── README.md
└── pom.xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment