{"id":18398857,"url":"https://github.com/mongodb-developer/mongodb-springboot3-kotlin","last_synced_at":"2025-04-14T10:52:47.651Z","repository":{"id":98127952,"uuid":"596064052","full_name":"mongodb-developer/mongodb-springboot3-kotlin","owner":"mongodb-developer","description":"Getting started App with Spring Boot 3 in Kotlin using MongoDB","archived":false,"fork":false,"pushed_at":"2023-02-13T14:12:02.000Z","size":93,"stargazers_count":12,"open_issues_count":0,"forks_count":4,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-28T00:06:39.014Z","etag":null,"topics":["backend","kotlin","mongodb","restful","springboot3"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mongodb-developer.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":"2023-02-01T11:47:48.000Z","updated_at":"2024-08-04T21:24:19.000Z","dependencies_parsed_at":"2023-03-13T16:05:09.890Z","dependency_job_id":null,"html_url":"https://github.com/mongodb-developer/mongodb-springboot3-kotlin","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/mongodb-developer%2Fmongodb-springboot3-kotlin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb-developer%2Fmongodb-springboot3-kotlin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb-developer%2Fmongodb-springboot3-kotlin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb-developer%2Fmongodb-springboot3-kotlin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mongodb-developer","download_url":"https://codeload.github.com/mongodb-developer/mongodb-springboot3-kotlin/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248868807,"owners_count":21174755,"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":["backend","kotlin","mongodb","restful","springboot3"],"created_at":"2024-11-06T02:24:40.347Z","updated_at":"2025-04-14T10:52:47.645Z","avatar_url":"https://github.com/mongodb-developer.png","language":"Kotlin","readme":"# Getting Started with backend development in Kotlin using Spring Boot 3 \u0026 MongoDB\n\n\u003e This is an introduction article on how to build a RESTful application in Kotlin using\n\u003e [Spring Boot 3](https://spring.io/) and [MongoDB Atlas](https://www.mongodb.com/atlas/database).\n\n## Introduction\n\nToday, we are going to build a basic RESTful application that does a little more than a CRUD\noperation, and for that, we will use:\n\n* `Spring Boot 3`, which is one of the popular frameworks based on Spring, allowing developers to\n  build production grades quickly.\n* `MongoDB`, which is a document oriented database, allowing developers to focus on building apps\n  rather than on [database schema](https://en.wikipedia.org/wiki/Database_schema).\n\n## Prerequisites\n\nThis is a getting-started article, so nothing much is needed as a prerequisite. But familiarity\nwith [Kotlin](https://kotlinlang.org/) as a programming language, plus a basic understanding\nof [Rest API](https://en.wikipedia.org/wiki/Representational_state_transfer)\nand [HTTP methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol), would be helpful.\n\nTo help with development activities, we will be\nusing [Jetbrains IntelliJ IDEA (Community Edition)](https://www.jetbrains.com/idea/download/).\n\n## HelloWorld app!\n\nBuilding a HelloWorld app in any programming language/technology, I believe, is the quickest and\neasiest way to get familiar with it. This helps you cover the basic concepts, like how to build,\nrun, debug, deploy, etc.\n\nSince we are using the community version of IDEA, we cannot create the `HelloWorld` project directly\nfrom IDE itself using the New Project. But we can use\nthe [Spring initializer app](https://start.spring.io/) instead, which allows us to create a Spring\nproject out of the box.\n\nOnce you are on the website, you can update the default selected parameters for the project, like\nthe name of the project, language, version of `Spring Boot`, etc., to something similar as shown\nbelow.\n\n![Spring initializer](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Spring_initializr_dbbfd7e79a.png)\n\nAnd since we want to create REST API with MongoDB as a database, let's add the dependency using the\nAdd Dependency button on the right.\n\n![Spring dependency](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Spring_Depdendency_bb8866de1c.png)\n\nAfter all the updates, our project settings will look like this.\n\n![Spring project](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Spring_With_Dependency_4137b2515f.png)\n\nNow we can download the project folder using the generate button and open it using the IDE. If we\nscan the project folder, we will only find one class — i.e., `HelloBackendWorldApplication.kt`,\nwhich has the `main` function, as well.\n\n![Sample Project](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Default_App_c843cf2216.png)\n\nThe next step is to print HelloWorld on the screen. Since we are building a restful\napplication, we will create a `GET` request API. So, let's add a function to act as a `GET` API\ncall.\n\n```kotlin\n@GetMapping(\"/hello\")\nfun hello(@RequestParam(value = \"name\", defaultValue = \"World\") name: String?): String {\n    return String.format(\"Hello %s!\", name)\n}\n```\n\nWe also need to add an annotation of `@RestController` to our `class` to make it a `Restful` client.\n\n```kotlin\n@SpringBootApplication\n@RestController\nclass HelloBackendWorldApplication {\n    @GetMapping(\"/hello\")\n    fun hello(): String {\n        return \"Hello World!\"\n    }\n}\n\nfun main(args: Array\u003cString\u003e) {\n    runApplication\u003cHelloBackendWorldApplication\u003e(*args)\n}\n```\n\nNow, let's run our project using the run icon from the toolbar.\n\n![Run icon image](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Run_icon_image_bdb6c52ca8.png)\n\nNow load https://localhost:8080/hello on the browser once the build is complete, and that will print\nHello World on your screen.\n\n![Hello World Output](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Hello_World_output_279aed0e43.png)\n\nAnd on cross-validating this from [Postman](https://www.postman.com), we can clearly understand that\nour `Get` API is working perfectly.  \n![Hello World Output](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Postman_output_216cb86538.png)\n\nIt's time to understand the basics of `Spring Boot` that made it so easy to create our first API\ncall.\n\n## What is Spring Boot ?\n\n\u003e [As per official docs](https://spring.io/projects/spring-boot#overview), Spring Boot makes it easy\n\u003e to create stand-alone, production-grade, Spring-based applications that you can \"just run.\"\n\nThis implies that it's a tool built on top of the Spring framework, allowing us to build web\napplications quickly.\n\n`Spring Boot` uses annotations, which do the heavy lifting in the background. A few of them, we have\nused already, like:\n\n1. `@SpringBootApplication`: This annotation is marked at class level, and declares to the code\n   reader (developer) and Spring that it's a Spring Boot project. It allows an enabling feature,\n   which can also be done using `@EnableAutoConfiguration`,`@ComponentScan`, and `@Configuration`.\n\n2. `@RequestMapping` and `@RestController`: This annotation provides the routing information.\n   Routing is nothing but a mapping of a `HTTP` request path (text after `host/`) to classes that\n   have the implementation of these across various `HTTP` methods.\n\nThese annotations are sufficient for building a basic application. Using Spring Boot, we will create\na RESTful web service with all business logic, but we don't have a data container that can store or\nprovide data to run these operations.\n\n## Introduction to MongoDB\n\nFor our app, we will be using MongoDB as the database. MongoDB is an open-source, cross-platform,\nand distributed document database, which allows building apps with flexible schema. This is great as\nwe can focus on building the app rather than defining the schema.\n\nWe can get started with MongoDB really quickly\nusing [MongoDB Atlas](https://www.mongodb.com/atlas/database), which is a database as a service in\nthe cloud and has a free forever tier.\n\nI recommend that you explore\nthe [MongoDB Jumpstart series](https://www.youtube.com/watch?v=RGfFpQF0NpE\u0026list=PL4RCxklHWZ9v2lcat4oEVGQhZg6r4IQGV)\nto get familiar with MongoDB and its various services in under 10 minutes.\n\n## Connecting with the Spring Boot app and MongoDB\n\nWith the basics of MongoDB covered, now let's connect our Spring Boot project to it. Connecting with\nMongoDB is really simple, thanks to the Spring Data MongoDB plugin.\n\nTo connect with MongoDB Atlas, we just need\na [database URL](https://www.mongodb.com/docs/guides/atlas/connection-string/) that can be added\nas a `spring.data.mongodb.uri` property in `application.properties` file. The connection string can\nbe found as shown below.\n\n![DB URL](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/find_Connect_Stream_URL_e7a6c2257a.gif)\n\nThe format for the connection string is:\n\n```shell\nspring.data.mongodb.uri = mongodb + srv ://\u003cusername\u003e:\u003cpwd\u003e@\u003ccluster\u003e.mongodb.net/\u003cdbname\u003e\n```\n\n![Connection URL](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Connect_Mongo_DB_Atlas_19305672d4.png)\n\n## Creating a CRUD RESTful app\n\nWith all the basics covered, now let's build a more complex application than HelloWorld! In this\napp, we will be covering all CRUD operations and tweaking them along the way to make it a more\nrealistic app. So, let's create a new project similar to the HelloWorld app we created earlier. And\nfor this app, we will use one of the sample datasets provided by MongoDB — one of my favourite\nfeatures that enables quick learning.\n\nYou can load\na [sample dataset](https://www.mongodb.com/developer/products/atlas/atlas-sample-datasets/) on Atlas\nas shown below:\n\n![sample_db](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/load_sample_dataset_95ce8126e0.png)\n\nWe will be using the `sample_restaurants` collection for our CRUD application. Before we start with\nthe actual CRUD operation, let's create the restaurant model class equivalent to it in the\ncollection.\n\n![model](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/model_from_compass_20b916a09a.png)\n\n```kotlin\n\n@Document(\"restaurants\")\ndata class Restaurant(\n    @Id\n    val id: ObjectId = ObjectId(),\n    val address: Address = Address(),\n    val borough: String = \"\",\n    val cuisine: String = \"\",\n    val grades: List\u003cGrade\u003e = emptyList(),\n    val name: String = \"\",\n    @Field(\"restaurant_id\")\n    val restaurantId: String = \"\"\n)\n\ndata class Address(\n    val building: String = \"\",\n    val street: String = \"\",\n    val zipcode: String = \"\",\n    @Field(\"coord\")\n    val coordinate: List\u003cDouble\u003e = emptyList()\n)\n\ndata class Grade(\n    val date: Date = Date(),\n    @Field(\"grade\")\n    val rating: String = \"\",\n    val score: Int = 0\n)\n```\n\nYou will notice there is nothing fancy about this class except for the annotation. These annotations\nhelp us to connect or co-relate classes with databases like:\n\n* `@Document`: This declares that this data class represents a document in Atlas.\n* `@Field`: This is used to define an alias name for a property in the document, like `coord` for\n  coordinate in `Address` model.\n\nNow let's create a repository class where we can define all methods through which we can access\ndata. `Spring Boot` has interface `MongoRepository`, which helps us with this.\n\n```kotlin\ninterface Repo : MongoRepository\u003cRestaurant, String\u003e {\n\n    fun findByRestaurantId(id: String): Restaurant?\n}\n```\n\nAfter that, we create a controller through which we can call these queries. Since this is a bigger\nproject, unlike the HelloWorld app, we will create a separate controller where the `MongoRepository`\ninstance is passed using `@Autowired`, which provides annotations-driven dependency injection.\n\n```kotlin\n@RestController\n@RequestMapping(\"/restaurants\")\nclass Controller(@Autowired val repo: Repo) {\n\n}\n``` \n\n### Read operation\n\nNow our project is ready to do some action, so let's count the number of restaurants in the\ncollection using `GetMapping`.\n\n```kotlin\n@RestController\n@RequestMapping(\"/restaurants\")\nclass Controller(@Autowired val repo: Repo) {\n\n    @GetMapping\n    fun getCount(): Int {\n        return repo.findAll().count()\n    }\n}\n```\n\n![model](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Read_72aa6d89de.png)\n\nTaking a step further to read the restaurant-based `restaurantId`. We will have to add a method in\nour repo as `restaurantId` is not marked `@Id` in the restaurant class.\n\n```kotlin\ninterface Repo : MongoRepository\u003cRestaurant, String\u003e {\n    fun findByRestaurantId(restaurantId: String): Restaurant?\n}\n``` \n\n```kotlin\n@GetMapping(\"/{id}\")\nfun getRestaurantById(@PathVariable(\"id\") id: String): Restaurant? {\n    return repo.findByRestaurantId(id)\n}\n```\n\nAnd again, we will be using [Postman](https://www.postman.com/) to validate the output against a\nrandom `restaurantId` from the sample dataset.\n\n![ready-id](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Read_By_Id_d1752a108b.png)\n\nLet's also validate this against a non-existing `restaurantId`.\n\n![ready-null](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Read_Null_637f97f167.png)\n\nAs expected, we haven't gotten any results, but the API response code is still 200, which is\nincorrect! So, let's fix this.\n\nIn order to have the correct response code, we will have to check the result before sending it back\nwith the correct response code.\n\n```kotlin\n    @GetMapping(\"/{id}\")\nfun getRestaurantById(@PathVariable(\"id\") id: String): ResponseEntity\u003cRestaurant\u003e {\n    val restaurant = repo.findByRestaurantId(id)\n    return if (restaurant != null) ResponseEntity.ok(restaurant) else ResponseEntity\n        .notFound().build()\n}\n```\n\n![ready-404](https://mongodb-devhub-cms.s3.us-west-1.amazonaws.com/Notfound_404_522b7f60ac.png)\n\n### Write operation\n\nTo add a new object to the collection, we can add a `write` function in the `repo` we created\nearlier, or we can use the inbuilt method `insert` provided by `MongoRepository`. Since we will be\nadding a new object to the collection, we'll be using `@PostMapping` for this.\n\n```kotlin\n    @PostMapping\nfun postRestaurant(): Restaurant {\n    val restaurant = Restaurant().copy(name = \"sample\", restaurantId = \"33332\")\n    return repo.insert(restaurant)\n}\n```\n\n### Update operation\n\nSpring doesn't have any specific in-built update similar to other CRUD operations, so we will be\nusing the read and write operation in combination to perform the update function.\n\n```kotlin\n    @PatchMapping(\"/{id}\")\nfun updateRestaurant(@PathVariable(\"id\") id: String): Restaurant? {\n    return repo.findByRestaurantId(restaurantId = id)?.let {\n        repo.save(it.copy(name = \"Update\"))\n    }\n}\n```\n\nThis is not an ideal way of updating items in the collection as it requires two operations and can\nbe improved further if we use the [MongoDB native driver](https://www.mongodb.com/docs/drivers/),\nwhich allows us to perform complicated operations with the minimum number of steps.\n\n### Delete operation\n\nDeleting a restaurant is also similar. We can use the `MongoRepository` delete function of the item\nfrom the collection, which takes the item as input.\n\n```kotlin\n    @DeleteMapping(\"/{id}\")\nfun deleteRestaurant(@PathVariable(\"id\") id: String) {\n    repo.findByRestaurantId(id)?.let {\n        repo.delete(it)\n    }\n}\n```\n\n## Summary\n\nThank you for reading and hopefully you find this article informative! The complete source code of\nthe app can be found on [GitHub](https://github.com/mongodb-developer/mongodb-springboot3-kotlin).\n\nIf you have any queries or comments, you can share them on\nthe [MongoDB forum](https://www.mongodb.com/community/forums/) or tweet\nme [@codeWithMohit](https://twitter.com/codeWithMohit).","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongodb-developer%2Fmongodb-springboot3-kotlin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmongodb-developer%2Fmongodb-springboot3-kotlin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongodb-developer%2Fmongodb-springboot3-kotlin/lists"}