{"id":22473337,"url":"https://github.com/arsy786/spring-boot-mongodb-rest-api","last_synced_at":"2026-05-11T06:02:48.246Z","repository":{"id":147956121,"uuid":"561489053","full_name":"arsy786/spring-boot-mongodb-rest-api","owner":"arsy786","description":"This is a guide about learning Spring Data MongoDB to develop a simple CRUD Expense Manager REST API.","archived":false,"fork":false,"pushed_at":"2024-03-16T03:31:09.000Z","size":5353,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-01T20:13:01.840Z","etag":null,"topics":["2022","guide","java","mongodb","project","rest-api","spring-boot"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/arsy786.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-11-03T20:00:55.000Z","updated_at":"2024-03-16T00:47:33.000Z","dependencies_parsed_at":"2024-03-22T11:01:52.712Z","dependency_job_id":null,"html_url":"https://github.com/arsy786/spring-boot-mongodb-rest-api","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arsy786%2Fspring-boot-mongodb-rest-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arsy786%2Fspring-boot-mongodb-rest-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arsy786%2Fspring-boot-mongodb-rest-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arsy786%2Fspring-boot-mongodb-rest-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arsy786","download_url":"https://codeload.github.com/arsy786/spring-boot-mongodb-rest-api/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245881198,"owners_count":20687688,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["2022","guide","java","mongodb","project","rest-api","spring-boot"],"created_at":"2024-12-06T12:22:30.114Z","updated_at":"2026-05-11T06:02:48.239Z","avatar_url":"https://github.com/arsy786.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Spring Boot MongoDB REST API\n\n\u003e ✅ **Part of the [Spring Boot Roadmap](https://github.com/arsy786/spring-boot-roadmap)** — a curated masterclass covering everything from Java basics to advanced Spring Boot practices and projects.\n\nIt is one of several interconnected repositories making up the broader [Spring Boot Roadmap](https://github.com/arsy786/spring-boot-roadmap), which provides a complete learning journey.\n\n---\n\nThis is a guide about learning Spring Data MongoDB to develop a simple CRUD Expense Manager REST API.\n\n## Table of Contents\n\n[0. Getting Started](#0-getting-started)\n\u003cbr\u003e\n[1. MongoDB](#1-mongodb)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[1.1 MongoDB Installation](#11-mongodb-installation)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[1.2 Mongosh vs. Studio3T](#12-mongosh-vs-studio3t)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[1.3 MongoDB Commands](#13-mongodb-commands)\n\u003cbr\u003e\n[2. REST API](#2-rest-api)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[2.1 Dependencies](#21-dependencies)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[2.2 Model](#22-model)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[2.3 Repository](#23-repository)\n\u003cbr\u003e\n\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;[2.4 Creating REST API (Service \u0026 Controller)](#24-creating-rest-api-service--controller)\n\n## 0. Getting Started\n\n### Prerequisites\n\n- Git\n- Java 11\n- Maven\n\n### Running the App\n\n1.  Open your terminal or command prompt.\n\n2.  Clone the repository using Git:\n\n    ```bash\n    git clone https://github.com/arsy786/spring-boot-mongodb-rest-api.git\n    ```\n\n3.  Navigate to the cloned repository's root directory:\n\n    ```bash\n    cd spring-boot-mongodb-rest-api\n    ```\n\n4.  Run the following Maven command to build and start the service:\n\n    ```bash\n    # For Maven\n    mvn spring-boot:run\n\n    # For Maven Wrapper\n    ./mvnw spring-boot:run\n    ```\n\nThe application should now be running on `localhost:8080`.\n\n### Database Configuration\n\n[2.1 Dependencies](#21-dependencies)\n\n## 1. MongoDB\n\n### 1.1 MongoDB Installation\n\nCan install from MongoDB website or the Mac terminal.\n\nWebsite: [Install MongoDB Community Edition](https://www.mongodb.com/docs/manual/administration/install-community/)\n\u003cbr\u003e\nTerminal: [How to install Mongodb 5 | latest MAC installation (YouTube/HiteshChoudhary)](https://www.youtube.com/watch?v=s1WQ0eEpqqg)\n\u003cbr\u003e\nCommon problem when installing via Terminal: [zsh: command not found: mongo](https://stackoverflow.com/questions/68695241/zsh-command-not-found-mongo)\n\n### 1.2 Mongosh vs. Studio3T\n\nCan use a shell (Terminal) or GUI to access MongoDB.\n\nMongoDB Shell (Mongosh) is the quickest way to connect, configure, query, and work with your MongoDB database. It acts as a command-line client of the MongoDB server.\n\nMongosh: [MongoDB Crash Course (YouTube/WebDevSimplified)](https://www.youtube.com/watch?v=ofme2o29ngU)\n\nStudio3T is an interactive tool for querying, optimizing, and analyzing your MongoDB data. Studio3T also has its own built-in mongo shell, IntelliShell, which offers live error highlighting and smart auto-completion.\n\nStudio3T: [Getting Started with Studio 3T | The GUI for MongoDB (YouTube/Studio3T)](https://www.youtube.com/watch?v=cKHumpkI7c8)\n\n### 1.3 MongoDB Commands\n\nMongoDB has some commonly used commands which have been neatly gathered for quick reference in: [MongoDB-Dark.pdf](https://github.com/arsy786/spring-boot-mongodb-rest-api/blob/master/MongoDB-Dark.pdf)\n\n## 2. REST API\n\n[Spring Data MongoDB Tutorial (ProgrammingTechie)](https://programmingtechie.com/2021/01/06/spring-data-mongodb-tutorial/)\n\n### 2.1 Dependencies\n\nYou can download the starter project with all the needed dependencies at Spring Initializr website with these dependencies:\n\n- Spring Web\n- Spring Data MongoDB\n- Lombok\n- Testcontainers\n\nYou can define the MongoDB properties by either using the MongoURI or by defining the host, username, password and database details:\n\n`application.properties`:\n\n```properties\n# Approach 1\nspring.data.mongodb.uri=mongodb://localhost:27017/expense-tracker\n\n# Approach 2\nspring.data.mongodb.host=localhost\nspring.data.mongodb.username=\u003cyour-username\u003e\nspring.data.mongodb.password=\u003cyour-password\u003e\nspring.data.mongodb.database=expense-tracker\n```\n\nNOTE: If authentication enabled, username and password must be provided.\n\n### 2.2 Model\n\n`expense.java`:\n\n```java\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@Document(\"expense\")\npublic class Expense {\n\n    @Id\n    private String id;\n\n    @Field(\"name\")\n    @Indexed(unique = true)\n    private String expenseName;\n\n    @Field(\"category\")\n    private ExpenseCategory expenseCategory;\n\n    @Field(\"amount\")\n    private BigDecimal expenseAmount;\n\n}\n```\n\n`ExpenseCategory.java`:\n\n```java\npublic enum ExpenseCategory {\n    ENTERTAINMENT, GROCERIES, RESTAURANT, UTILITIES, MISC\n}\n```\n\n- Normal POJO class with annotations.\n- Lombok annotations reduce boilerplate code.\n- To define a Model Class as a MongoDB Document, we are going to use the @Document(“expense”) where expense is the name of the Document.\n- @Id represents a unique identifier for our Document.\n- We can represent different fields inside the Document using the @Field annotation.\n- By default, Spring Data creates the field inside the document using the fieldName of the model class (Eg: expenseName), but we can override this by providing the required value to the annotation eg: @Field(“name”).\n- To be able to easily retrieve the documents, we can also create an index using the @Indexed annotaion.\n- We can also specify the unique=true property to make sure that this field is unique.\n\n### 2.3 Repository\n\nSpring Data MongoDB provides an interface called MongoRepository which provides an API to perform read and write operations to MongoDB.\n\n`ExpenseRepository.java`:\n\n```java\n@Repository\npublic interface ExpenseRepository extends MongoRepository\u003cExpense, String\u003e {\n    @Query(\"{'name': ?0}\")\n    Optional\u003cExpense\u003e findByName(String name);\n}\n```\n\nWe can also perform custom queries using the @Query annotation and by passing in the required query we need to run to this annotation.\nSpring Data will inject the value of the name field into the query, in the place of the ?0 placeholder.\n\n### 2.4 Creating REST API (Service \u0026 Controller)\n\nNeed to add the business logic in the Service layer.\n\n`ExpenseService.java`:\n\n```java\n@Service\n@RequiredArgsConstructor\npublic class ExpenseService {\n\n    private final ExpenseRepository expenseRepository;\n\n    public void addExpense(Expense expense) {\n        expenseRepository.insert(expense);\n    }\n\n    public void updateExpense(Expense expense) {\n        Expense savedExpense = expenseRepository.findById(expense.getId()).orElseThrow(\n                () -\u003e new RuntimeException(String.format(\"Cannot Find Expense by ID %s\", expense.getId())));\n\n        savedExpense.setExpenseName(expense.getExpenseName());\n        savedExpense.setExpenseCategory(expense.getExpenseCategory());\n        savedExpense.setExpenseAmount(expense.getExpenseAmount());\n\n        expenseRepository.save(expense);\n    }\n\n    public Expense getExpense(String name) {\n        return expenseRepository.findByName(name).orElseThrow(\n                () -\u003e new RuntimeException(String.format(\"Cannot Find Expense by Name - %s\", name)));\n    }\n\n    public List\u003cExpense\u003e getAllExpenses() {\n        return expenseRepository.findAll();\n    }\n\n    public void deleteExpense(String id) {\n        expenseRepository.deleteById(id);\n    }\n}\n```\n\nNeed to add the API Endpoints in the Controller layer.\n\n`ExpenseController.java`:\n\n```java\n@RestController\n@RequestMapping(\"/expense\")\n@RequiredArgsConstructor\npublic class ExpenseController {\n\n    private final ExpenseService expenseService;\n\n    @PostMapping(\"/\")\n    public ResponseEntity addExpense(@RequestBody Expense expense) {\n        expenseService.addExpense(expense);\n        return ResponseEntity.status(HttpStatus.CREATED).build();\n    }\n\n    @PutMapping\n    public ResponseEntity updateExpense(@RequestBody Expense expense) {\n        expenseService.updateExpense(expense);\n        return ResponseEntity.status(HttpStatus.OK).build();\n    }\n\n    @GetMapping\n    public ResponseEntity\u003cList\u003cExpense\u003e\u003e getAllExpenses() {\n        return ResponseEntity.ok(expenseService.getAllExpenses());\n    }\n\n    @GetMapping(\"/{name}\")\n    public ResponseEntity getExpenseByName(@PathVariable String name) {\n        return ResponseEntity.ok(expenseService.getExpense(name));\n    }\n\n    @DeleteMapping(\"/{id}\")\n    public ResponseEntity deleteExpense(@PathVariable String id) {\n        expenseService.deleteExpense(id);\n        return ResponseEntity.noContent().build();\n    }\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farsy786%2Fspring-boot-mongodb-rest-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farsy786%2Fspring-boot-mongodb-rest-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farsy786%2Fspring-boot-mongodb-rest-api/lists"}