├── .gitignore ├── LICENSE ├── Readme.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src └── main └── kotlin ├── Create.kt ├── Delete.kt ├── Models.kt ├── Read.kt ├── Setup.kt └── Update.kt /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea/ 9 | *.iws 10 | *.iml 11 | *.ipr 12 | out/ 13 | !**/src/main/**/out/ 14 | !**/src/test/**/out/ 15 | 16 | ### Eclipse ### 17 | .apt_generated 18 | .classpath 19 | .factorypath 20 | .project 21 | .settings 22 | .springBeans 23 | .sts4-cache 24 | bin/ 25 | !**/src/main/**/bin/ 26 | !**/src/test/**/bin/ 27 | 28 | ### NetBeans ### 29 | /nbproject/private/ 30 | /nbbuild/ 31 | /dist/ 32 | /nbdist/ 33 | /.nb-gradle/ 34 | 35 | ### VS Code ### 36 | .vscode/ 37 | 38 | ### Mac OS ### 39 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Getting Started With the MongoDB Kotlin Driver 2 | 3 | > This is an introductory article on how to build an application in Kotlin using [MongoDB Atlas](https://www.mongodb.com/atlas/database) and 4 | > the [MongoDB Kotlin driver](https://github.com/mongodb-developer/kotlin-driver-quick-start), the latest addition to our list of official drivers. 5 | > Together, we'll build a CRUD application that covers the basics of how to use MongoDB as a database, while leveraging the benefits of Kotlin as a 6 | > programming language, like data classes, coroutines, and flow. 7 | 8 | ## Prerequisites 9 | 10 | This is a getting-started article. Therefore, not much is needed as a prerequisite, but familiarity with Kotlin as a programming language will be 11 | helpful. 12 | 13 | Also, we need an [Atlas account](https://www.mongodb.com/cloud/atlas/register), which is free forever. Create an account if you haven't got one. This 14 | provides MongoDB as a cloud database and much more. Later in this tutorial, we'll use this account to create a new cluster, load a dataset, and 15 | eventually query against it. 16 | 17 | In general, MongoDB is an open-source, cross-platform, and distributed document database that allows building apps with flexible schema. In case you 18 | are not familiar with it or would like a quick recap, I recommend exploring 19 | the [MongoDB Jumpstart series](https://www.youtube.com/watch?v=RGfFpQF0NpE&list=PL4RCxklHWZ9v2lcat4oEVGQhZg6r4IQGV) to get familiar with MongoDB and 20 | its various services in under 10 minutes. Or if you prefer to read, then you can follow 21 | our [guide](https://www.mongodb.com/docs/atlas/getting-started/). 22 | 23 | And last, to aid our development activities, we will be using [Jetbrains IntelliJ IDEA (Community Edition)](https://www.jetbrains.com/idea/download/), 24 | which has default support for the Kotlin language. 25 | 26 | ## MongoDB Kotlin driver vs MongoDB Realm Kotlin SDK 27 | 28 | Before we start, I would like to touch base on [Realm Kotlin SDK](https://www.mongodb.com/docs/realm/sdk/kotlin/), one of the SDKs used to create 29 | client-side mobile applications using the MongoDB ecosystem. It shouldn't be confused with 30 | the [MongoDB Kotlin driver](https://www.mongodb.com/docs/drivers/kotlin/coroutine/current/) for server-side programming. 31 | The [MongoDB Kotlin driver](https://www.mongodb.com/docs/drivers/kotlin/coroutine/current/), a language driver, enables you to seamlessly interact 32 | with [Atlas](https://www.mongodb.com/atlas/database), a cloud database, with the benefits of the Kotlin language paradigm. It's appropriate to create 33 | backend apps, scripts, etc. 34 | 35 | To make learning more meaningful and practical, we'll be building a CRUD application. Feel free to check out our 36 | [Github repo](https://github.com/mongodb-developer/kotlin-driver-quick-start) if you would like to follow along together. So, without further ado, 37 | let's get started. 38 | 39 | ## Create a project 40 | 41 | To create the project, we can use the project wizard, which can be found under the `File` menu options. Then, select `New`, followed by `Project`. 42 | This will open the `New Project` screen, as shown below, then update the project and language to Kotlin. 43 | 44 | ![Project wizard](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltbce8e7adda583e3e/648793838b23a5b3d5052b69/Screenshot_2023-06-12_at_09.34.09.png) 45 | 46 | After the initial Gradle sync, our project is ready to run. So, let's give it a try using the run icon in the menu bar, or simply press CTRL + R on 47 | Mac. Currently, our project won't do much apart from printing `Hello World!` and arguments supplied, but the `BUILD SUCCESSFUL` message in the run 48 | console is what we're looking for, which tells us that our project setup is complete. 49 | 50 | ![build success](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt97a67a3d4a402196/64879383d40ad08ec16808a9/Screenshot_2023-06-12_at_13.42.38.png) 51 | 52 | Now, the next step is to add the Kotlin driver to our project, which allows us to interact 53 | with [MongoDB Atlas](https://www.mongodb.com/atlas/database). 54 | 55 | ## Adding the MongoDB Kotlin driver 56 | 57 | Adding the driver to the project is simple and straightforward. Just update the `dependencies` block with the Kotlin driver dependency in the build 58 | file — i.e., `build.gradle`. 59 | 60 | ```groovy 61 | dependencies { 62 | // Kotlin coroutine dependency 63 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4") 64 | 65 | // MongoDB Kotlin driver dependency 66 | implementation("org.mongodb:mongodb-driver-kotlin-coroutine:4.10.1") 67 | } 68 | ``` 69 | 70 | And now, we are ready to connect with [MongoDB Atlas](https://www.mongodb.com/atlas/database) using the Kotlin driver. 71 | 72 | ## Connecting to the database 73 | 74 | To connect with the database, we first need the `Connection URI` that can be found by pressing `connect to cluster` in 75 | our [Atlas account](https://www.mongodb.com/cloud/atlas/register), as shown below. 76 | 77 | ![image](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt1d92c6f1c6654b04/648c2ff42429af5fa2f487e4/atlas_connection_copy_string_kotlin.png) 78 | 79 | For more details, you can also refer to our [documentation](https://www.mongodb.com/docs/guides/atlas/connection-string/). 80 | 81 | With the connection URI available, the next step is to create a Kotlin file. `Setup.kt` is where we write the code for connecting 82 | to [MongoDB Atlas](https://www.mongodb.com/atlas/database). 83 | 84 | ![Setup.kt file](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltdc533d1983ce2f87/6488261e8b23a52669052cee/Screenshot_2023-06-13_at_09.17.29.png) 85 | 86 | Connection with our database can be split into two steps. First, we create a MongoClient instance using `Connection URI`. 87 | 88 | ```kotlin 89 | val connectionString = "mongodb+srv://:@cluster0.sq3aiau.mongodb.net/?retryWrites=true&w=majority" 90 | val client = MongoClient.create(connectionString = connectString) 91 | ``` 92 | 93 | And second, use client to connect with the database, `sample_restaurants`, which is a sample dataset for 94 | restaurants. A [sample dataset](https://www.mongodb.com/docs/atlas/sample-data/) is a great way to explore the platform and build a more realistic POC 95 | to validate your ideas. To learn how to seed your first Atlas database with sample 96 | data, [visit the docs](https://www.mongodb.com/docs/atlas/sample-data/). 97 | 98 | ```kotlin 99 | val databaseName = "sample_restaurants" 100 | val db: MongoDatabase = client.getDatabase(databaseName = databaseName) 101 | ``` 102 | 103 | Hardcoding `connectionString` isn't a good approach and can lead to security risks or an inability to provide role-based access. To avoid such issues 104 | and follow the best practices, we will be using environment variables. Other common approaches are the use of Vault, build configuration variables, 105 | and CI/CD environment variables. 106 | 107 | To add environment variables, use `Modify run configuration`, which can be found by right-clicking on the file. 108 | 109 | ![add environment variable](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt8438bbb2ace0979e/64882bac83c7fb1a685f3d1b/Screenshot_2023-06-13_at_09.38.49.png) 110 | 111 | Together with code to access the environment variable, our final code looks like this. 112 | 113 | ```kotlin 114 | suspend fun setupConnection( 115 | databaseName: String = "sample_restaurants", 116 | connectionEnvVariable: String = "MONGODB_URI" 117 | ): MongoDatabase? { 118 | val connectString = if (System.getenv(connectionEnvVariable) != null) { 119 | System.getenv(connectionEnvVariable) 120 | } else { 121 | "mongodb+srv://:@cluster0.sq3aiau.mongodb.net/?retryWrites=true&w=majority" 122 | } 123 | 124 | val client = MongoClient.create(connectionString = connectString) 125 | val database = client.getDatabase(databaseName = databaseName) 126 | 127 | return try { 128 | // Send a ping to confirm a successful connection 129 | val command = Document("ping", BsonInt64(1)) 130 | database.runCommand(command) 131 | println("Pinged your deployment. You successfully connected to MongoDB!") 132 | database 133 | } catch (me: MongoException) { 134 | System.err.println(me) 135 | null 136 | } 137 | } 138 | ``` 139 | 140 | > In the code snippet above, we still have the ability to use a hardcoded string. This is only done for demo purposes, allowing you to use a 141 | > connection URI directly for ease and to run this via any online editor. But it is strongly recommended to avoid hardcoding a connection URI. 142 | 143 | With the `setupConnection` function ready, let's test it and query the database for the collection count and name. 144 | 145 | ```kotlin 146 | suspend fun listAllCollection(database: MongoDatabase) { 147 | 148 | val count = database.listCollectionNames().count() 149 | println("Collection count $count") 150 | 151 | print("Collection in this database are -----------> ") 152 | database.listCollectionNames().collect { print(" $it") } 153 | } 154 | ``` 155 | 156 | Upon running that code, our output looks like this: 157 | 158 | ![list collection output](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt5a670a8008abba48/648835185953929729a04668/Screenshot_2023-06-13_at_10.21.15.png) 159 | 160 | By now, you may have noticed that we are using the `suspend` keyword with `listAllCollection()`. `listCollectionNames()` is an asynchronous function 161 | as it interacts with the database and therefore would ideally run on a different thread. And since the MongoDB Kotlin driver 162 | supports [Coroutines](https://kotlinlang.org/docs/coroutines-guide.html), the 163 | native [Kotlin asynchronous language paradigm](https://kotlinlang.org/docs/async-programming.html), we can benefit from it by using `suspend` 164 | functions. 165 | 166 | Similarly, to drop collections, we use the `suspend` function. 167 | 168 | ```kotlin 169 | suspend fun dropCollection(database: MongoDatabase) { 170 | database.getCollection(collectionName = "restaurants").drop() 171 | } 172 | ``` 173 | 174 | With this complete, we are all set to start working on our CRUD application. So to start with, we need to create a `data` class that represents 175 | restaurant information that our app saves into the database. 176 | 177 | ```kotlin 178 | data class Restaurant( 179 | @BsonId 180 | val id: ObjectId, 181 | val address: Address, 182 | val borough: String, 183 | val cuisine: String, 184 | val grades: List, 185 | val name: String, 186 | @BsonProperty("restaurant_id") 187 | val restaurantId: String 188 | ) 189 | 190 | data class Address( 191 | val building: String, 192 | val street: String, 193 | val zipcode: String, 194 | val coord: List 195 | ) 196 | 197 | data class Grade( 198 | val date: LocalDateTime, 199 | val grade: String, 200 | val score: Int 201 | ) 202 | ``` 203 | 204 | In the above code snippet, we used two annotations: 205 | 206 | 1. `@BsonId`, which represents the unique identity or `_id` of a document. 207 | 2. `@BsonProperty`, which creates an alias for keys in the document — for example, `restaurantId` represents `restaurant_id`. 208 | 209 | > Note: Our `Restaurant` data class here is an exact replica of a restaurant document in the sample dataset, but a few fields can be skipped or marked 210 | > as optional — e.g., `grades` and `address` — while maintaining the ability to perform CRUD operations. We are able to do so, as MongoDB’s document 211 | > model allows flexible schema for our data. 212 | 213 | ## Create 214 | 215 | With all the heavy lifting done (10 lines of code for connecting), adding a new document to the database is really simple and can be done with one 216 | line of code using `insertOne`. So, let's create a new file called `Create.kt`, which will contain all the create operations. 217 | 218 | ```kotlin 219 | suspend fun addItem(database: MongoDatabase) { 220 | 221 | val collection = database.getCollection(collectionName = "restaurants") 222 | val item = Restaurant( 223 | id = ObjectId(), 224 | address = Address( 225 | building = "Building", street = "street", zipcode = "zipcode", coord = 226 | listOf(Random.nextDouble(), Random.nextDouble()) 227 | ), 228 | borough = "borough", 229 | cuisine = "cuisine", 230 | grades = listOf( 231 | Grade( 232 | date = LocalDateTime.now(), 233 | grade = "A", 234 | score = Random.nextInt() 235 | ) 236 | ), 237 | name = "name", 238 | restaurantId = "restaurantId" 239 | ) 240 | 241 | collection.insertOne(item).also { 242 | println("Item added with id - ${it.insertedId}") 243 | } 244 | } 245 | ``` 246 | 247 | When we run it, the output on the console is: 248 | 249 | ![insert one](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt1d124cbfb185d7d6/648ae0b2359ef0161360df47/Screenshot_2023-06-15_at_10.49.33.png) 250 | 251 | > Again, don't forget to add an environment variable again for this file, if you had trouble while running it. 252 | 253 | If we want to add multiple documents to the collection, we can use `insertMany`, which is recommended over running `insertOne` in a loop. 254 | 255 | ```kotlin 256 | suspend fun addItems(database: MongoDatabase) { 257 | val collection = database.getCollection(collectionName = "restaurants") 258 | val newRestaurants = collection.find().first().run { 259 | listOf( 260 | this.copy( 261 | id = ObjectId(), name = "Insert Many Restaurant first", restaurantId = Random 262 | .nextInt().toString() 263 | ), 264 | this.copy( 265 | id = ObjectId(), name = "Insert Many Restaurant second", restaurantId = Random 266 | .nextInt().toString() 267 | ) 268 | ) 269 | } 270 | 271 | collection.insertMany(newRestaurants).also { 272 | println("Total items added ${it.insertedIds.size}") 273 | } 274 | } 275 | 276 | ``` 277 | 278 | ![Insert many output](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt02fc3f33de844c88/648ae1ce2c4f87306c1b12ce/Screenshot_2023-06-15_at_11.02.48.png) 279 | 280 | With these outputs on the console, we can say that the data has been added successfully. 281 | 282 | But what if we want to see the object in the database? One way is with a read operation, which we would do shortly or 283 | use [MongoDB Compass](https://www.mongodb.com/products/compass) to view the information. 284 | 285 | [MongoDB Compass](https://www.mongodb.com/products/compass) is a free, interactive GUI tool for querying, optimizing, and analyzing the MongoDB data 286 | from your system. To get started, [download](https://www.mongodb.com/try/download/shell) the tool and use the `connectionString` to connect with the 287 | database. 288 | 289 | ![MongoDB compass](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt72fd049dd230ea55/648ae40e1fb2d38f0e495940/Screenshot_2023-06-15_at_11.12.23.png) 290 | 291 | ## Read 292 | 293 | To read the information from the database, we can use the `find` operator. Let's begin by reading any document. 294 | 295 | ```kotlin 296 | val collection = database.getCollection(collectionName = "restaurants") 297 | collection.find().limit(1).collect { 298 | println(it) 299 | } 300 | ``` 301 | 302 | The `find` operator returns a list of results, but since we are only interested in a single document, we can use the `limit` operator in conjunction 303 | to limit our result set. In this case, it would be a single document. 304 | 305 | If we extend this further and want to read a specific document, we can add filter parameters over the top of it: 306 | 307 | ```kotlin 308 | val queryParams = Filters 309 | .and( 310 | listOf( 311 | eq("cuisine", "American"), 312 | eq("borough", "Queens") 313 | ) 314 | ) 315 | ``` 316 | 317 | Or, we can use any of the operators from our [list](https://www.mongodb.com/docs/manual/reference/operator/query/). The final code looks like this. 318 | 319 | ```kotlin 320 | suspend fun readSpecificDocument(database: MongoDatabase) { 321 | val collection = database.getCollection(collectionName = "restaurants") 322 | val queryParams = Filters 323 | .and( 324 | listOf( 325 | eq("cuisine", "American"), 326 | eq("borough", "Queens") 327 | ) 328 | ) 329 | 330 | 331 | collection 332 | .find(queryParams) 333 | .limit(2) 334 | .collect { 335 | println(it) 336 | } 337 | 338 | } 339 | ``` 340 | 341 | For the output, we see this: 342 | 343 | ![read specific doc output](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltd837ac1a039ae43f/648ae83f0f2d9b551eed55e2/Screenshot_2023-06-15_at_11.30.20.png) 344 | 345 | > Don't forget to add the environment variable again for this file, if you had trouble while running it. 346 | 347 | Another practical use case that comes with a read operation is how to add pagination to the results. This can be done with the `limit` and `offset` 348 | operators. 349 | 350 | ```kotlin 351 | suspend fun readWithPaging(database: MongoDatabase, offset: Int, pageSize: Int) { 352 | val collection = database.getCollection(collectionName = "restaurants") 353 | val queryParams = Filters 354 | .and( 355 | listOf( 356 | eq(Restaurant::cuisine.name, "American"), 357 | eq(Restaurant::borough.name, "Queens") 358 | ) 359 | ) 360 | 361 | collection 362 | .find(queryParams) 363 | .limit(pageSize) 364 | .skip(offset) 365 | .collect { 366 | println(it) 367 | } 368 | } 369 | ``` 370 | 371 | But with this approach, often, the query response time increases with value of the `offset`. To overcome this, we can benefit by creating an `Index`, 372 | as shown below. 373 | 374 | ```kotlin 375 | val collection = database.getCollection(collectionName = "restaurants") 376 | val options = IndexOptions().apply { 377 | this.name("restaurant_id_index") 378 | this.background(true) 379 | } 380 | 381 | collection.createIndex( 382 | keys = Indexes.ascending("restaurant_id"), 383 | options = options 384 | ) 385 | ``` 386 | 387 | ## Update 388 | 389 | Now, let's discuss how to edit/update an existing document. Again, let's quickly create a new Kotlin file, `Update.Kt`. 390 | 391 | In general, there are two ways of updating any document: 392 | 393 | * Perform an **update** operation, which allows us to update specific fields of the matching documents without impacting the other fields. 394 | * Perform a **replace** operation to replace the matching document with the new document. 395 | 396 | For this exercise, we'll use the document we created earlier with the create operation `{restaurant_id: "restaurantId"}` and update 397 | the `restaurant_id` with a more realistic value. Let's split this into two sub-tasks for clarity. 398 | 399 | First, using `Filters`, we query to filter the document, similar to the read operation earlier. 400 | 401 | ```kotlin 402 | val collection = db.getCollection("restaurants") 403 | val queryParam = Filters.eq("restaurant_id", "restaurantId") 404 | ``` 405 | 406 | Then, we can set the `restaurant_id` with a random integer value using `Updates`. 407 | 408 | ```kotlin 409 | val updateParams = Updates.set("restaurant_id", Random.nextInt().toString()) 410 | ``` 411 | 412 | And finally, we use `updateOne` to update the document in an atomic operation. 413 | 414 | ```kotlin 415 | collection.updateOne(filter = queryParam, update = updateParams).also { 416 | println("Total docs modified ${it.matchedCount} and fields modified ${it.modifiedCount}") 417 | } 418 | ``` 419 | 420 | In the above example, we were already aware of which document we wanted to update — the restaurant with an id `restauratantId` — but there could be a 421 | few use cases where that might not be the situation. In such cases, we would first look up the document and then update it. `findOneAndUpdate` can be 422 | handy. It allows you to combine both of these processes into an atomic operation, unlocking additional performance. 423 | 424 | Another variation of the same could be updating multiple documents with one call. `updateMany` is useful for such use cases — for example, if we want 425 | to update the `cuisine` of all restaurants to your favourite type of cuisine and `borough` to Brooklyn. 426 | 427 | ```kotlin 428 | suspend fun updateMultipleDocuments(db: MongoDatabase) { 429 | val collection = db.getCollection("restaurants") 430 | val queryParam = Filters.eq(Restaurant::cuisine.name, "Chinese") 431 | val updateParams = Updates.combine( 432 | Updates.set(Restaurant::cuisine.name, "Indian"), 433 | Updates.set(Restaurant::borough.name, "Brooklyn") 434 | ) 435 | 436 | collection.updateMany(filter = queryParam, update = updateParams).also { 437 | println("Total docs matched ${it.matchedCount} and modified ${it.modifiedCount}") 438 | } 439 | } 440 | ``` 441 | 442 | In these examples, we used `set` and `combine` with `Updates`. But there are many more types of update operator to explore that allow us to do many 443 | intuitive operations, like set the currentDate or timestamp, increase or decrease the value of the field, and so on. To learn more about the different 444 | types of update operators you can perform with Kotlin and MongoDB, refer to 445 | our [docs](https://mongodb.github.io/mongo-java-driver/4.9/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html). 446 | 447 | ## Delete 448 | 449 | Now, let's explore one final CRUD operation: delete. We'll start by exploring how to delete a single document. To do this, we'll 450 | use `findOneAndDelete` instead of `deleteOne`. As an added benefit, this also returns the deleted document as output. In our example, we delete the 451 | restaurant: 452 | 453 | ```kotlin 454 | val collection = db.getCollection(collectionName = "restaurants") 455 | val queryParams = Filters.eq("restaurant_id", "restaurantId") 456 | 457 | collection.findOneAndDelete(filter = queryParams).also { 458 | it?.let { 459 | println(it) 460 | } 461 | } 462 | ``` 463 | 464 | ![delete output](https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blta4bb9c39c2356306/6489bf30352ac64eebda33c6/Screenshot_2023-06-14_at_14.21.37.png) 465 | 466 | To delete multiple documents, we can use `deleteMany`. We can, for example, use this to delete all the data we created earlier with our create 467 | operation. 468 | 469 | ```kotlin 470 | suspend fun deleteRestaurants(db: MongoDatabase) { 471 | val collection = db.getCollection(collectionName = "restaurants") 472 | 473 | val queryParams = Filters.or( 474 | listOf( 475 | Filters.regex(Restaurant::name.name, Pattern.compile("^Insert")), 476 | Filters.regex("restaurant_id", Pattern.compile("^restaurant")) 477 | ) 478 | ) 479 | collection.deleteMany(filter = queryParams).also { 480 | println("Document deleted : ${it.deletedCount}") 481 | } 482 | } 483 | ``` 484 | 485 | ## Summary 486 | 487 | Congratulations! You now know how to set up your first Kotlin application with MongoDB and perform CRUD operations. The complete source code of the 488 | app can be found on [GitHub](https://github.com/mongodb-developer/kotlin-driver-quick-start). 489 | 490 | If you have any feedback on your experience working with the MongoDB Kotlin driver, please submit a comment in our 491 | user [feedback portal](https://feedback.mongodb.com/) or reach out to me on Twitter: [@codeWithMohit](https://twitter.com/codeWithMohit). -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("org.jetbrains.kotlin.jvm") version "1.8.0" 3 | id("application") 4 | } 5 | 6 | group = "org.example" 7 | version = "1.0-SNAPSHOT" 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4") 15 | implementation("org.mongodb:mongodb-driver-kotlin-coroutine:4.10.1") 16 | implementation("org.slf4j:slf4j-simple:1.7.9") 17 | 18 | testImplementation("org.jetbrains.kotlin:kotlin-test") 19 | } 20 | 21 | tasks.withType { 22 | useJUnitPlatform() 23 | } 24 | 25 | kotlin { 26 | jvmToolchain(11) 27 | } 28 | 29 | application { 30 | mainClassName = "SetupKt" 31 | } 32 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mongodb-developer/kotlin-driver-quick-start/c236e4f433c4905dcb5fc0c8c9269145aacada8f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlin-driver-quick-start" 2 | -------------------------------------------------------------------------------- /src/main/kotlin/Create.kt: -------------------------------------------------------------------------------- 1 | import com.mongodb.kotlin.client.coroutine.MongoDatabase 2 | import kotlinx.coroutines.flow.first 3 | import kotlinx.coroutines.runBlocking 4 | import org.bson.types.ObjectId 5 | import java.time.LocalDateTime 6 | import kotlin.random.Random 7 | 8 | fun main() { 9 | runBlocking { 10 | setupConnection()?.let { db: MongoDatabase -> 11 | addItem(database = db) 12 | addItems(database = db) 13 | } 14 | } 15 | } 16 | 17 | suspend fun addItem(database: MongoDatabase) { 18 | 19 | val collection = database.getCollection(collectionName = "restaurants") 20 | val item = Restaurant( 21 | id = ObjectId(), 22 | address = Address( 23 | building = "Building", street = "street", zipcode = "zipcode", coord = 24 | listOf(Random.nextDouble(), Random.nextDouble()) 25 | ), 26 | borough = "borough", 27 | cuisine = "cuisine", 28 | grades = listOf( 29 | Grade( 30 | date = LocalDateTime.now(), 31 | grade = "A", 32 | score = Random.nextInt() 33 | ) 34 | ), 35 | name = "name", 36 | restaurantId = "restaurantId" 37 | ) 38 | 39 | collection.insertOne(item).also { 40 | println("Item added with id - ${it.insertedId}") 41 | } 42 | 43 | } 44 | 45 | suspend fun addItems(database: MongoDatabase) { 46 | val collection = database.getCollection(collectionName = "restaurants") 47 | val newRestaurants = collection.find().first().run { 48 | listOf( 49 | this.copy( 50 | id = ObjectId(), name = "Insert Many Restaurant first", restaurantId = Random 51 | .nextInt().toString() 52 | ), 53 | this.copy( 54 | id = ObjectId(), name = "Insert Many Restaurant second", restaurantId = Random 55 | .nextInt().toString() 56 | ) 57 | ) 58 | } 59 | 60 | collection.insertMany(newRestaurants).also { 61 | println("Total items added ${it.insertedIds.size}") 62 | } 63 | } 64 | 65 | 66 | -------------------------------------------------------------------------------- /src/main/kotlin/Delete.kt: -------------------------------------------------------------------------------- 1 | import com.mongodb.client.model.Filters 2 | import com.mongodb.kotlin.client.coroutine.MongoDatabase 3 | import kotlinx.coroutines.runBlocking 4 | import java.util.regex.Pattern 5 | 6 | fun main() { 7 | runBlocking { 8 | setupConnection()?.let { db: MongoDatabase -> 9 | deleteRestaurant(db) 10 | deleteRestaurants(db) 11 | } 12 | } 13 | 14 | } 15 | 16 | suspend fun deleteRestaurant(db: MongoDatabase) { 17 | val collection = db.getCollection(collectionName = "restaurants") 18 | val queryParams = Filters.eq("restaurant_id", "restaurantId") 19 | 20 | collection.findOneAndDelete(filter = queryParams).also { 21 | it?.let { 22 | println(it) 23 | } 24 | } 25 | } 26 | 27 | suspend fun deleteRestaurants(db: MongoDatabase) { 28 | val collection = db.getCollection(collectionName = "restaurants") 29 | 30 | val queryParams = Filters.or( 31 | listOf( 32 | Filters.regex(Restaurant::name.name, Pattern.compile("^Insert")), 33 | Filters.regex("restaurant_id", Pattern.compile("^restaurant")) 34 | ) 35 | ) 36 | collection.deleteMany(filter = queryParams).also { 37 | println("Document deleted : ${it.deletedCount}") 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/kotlin/Models.kt: -------------------------------------------------------------------------------- 1 | import org.bson.codecs.pojo.annotations.BsonId 2 | import org.bson.codecs.pojo.annotations.BsonProperty 3 | import org.bson.types.ObjectId 4 | import java.time.LocalDateTime 5 | 6 | data class Restaurant( 7 | @BsonId 8 | val id: ObjectId, 9 | val address: Address, 10 | val borough: String, 11 | val cuisine: String, 12 | val grades: List, 13 | val name: String, 14 | @BsonProperty("restaurant_id") 15 | val restaurantId: String 16 | ) 17 | 18 | data class Address( 19 | val building: String, 20 | val street: String, 21 | val zipcode: String, 22 | val coord: List 23 | ) 24 | 25 | data class Grade( 26 | val date: LocalDateTime, 27 | val grade: String, 28 | val score: Int 29 | ) 30 | -------------------------------------------------------------------------------- /src/main/kotlin/Read.kt: -------------------------------------------------------------------------------- 1 | import com.mongodb.client.model.Filters 2 | import com.mongodb.client.model.Filters.eq 3 | import com.mongodb.client.model.IndexOptions 4 | import com.mongodb.client.model.Indexes 5 | import com.mongodb.client.model.Sorts 6 | import com.mongodb.kotlin.client.coroutine.MongoDatabase 7 | import kotlinx.coroutines.runBlocking 8 | 9 | fun main() { 10 | 11 | runBlocking { 12 | setupConnection()?.let { db: MongoDatabase -> 13 | readAnyDocument(database = db) 14 | readSpecificDocument(database = db) 15 | readWithPaging(database = db, offset = 2, pageSize = 2) 16 | readWithIndex(database = db) 17 | } 18 | } 19 | } 20 | 21 | suspend fun readAnyDocument(database: MongoDatabase) { 22 | val collection = database.getCollection(collectionName = "restaurants") 23 | collection.find().limit(1).collect { 24 | println(it) 25 | } 26 | } 27 | 28 | suspend fun readSpecificDocument(database: MongoDatabase) { 29 | val collection = database.getCollection(collectionName = "restaurants") 30 | val queryParams = Filters 31 | .and( 32 | listOf( 33 | eq("cuisine", "American"), 34 | eq("borough", "Queens") 35 | ) 36 | ) 37 | 38 | 39 | collection 40 | .find(queryParams) 41 | .limit(2) 42 | .collect { 43 | println(it) 44 | } 45 | 46 | } 47 | 48 | suspend fun readWithPaging(database: MongoDatabase, offset: Int, pageSize: Int) { 49 | val collection = database.getCollection(collectionName = "restaurants") 50 | val queryParams = Filters 51 | .and( 52 | listOf( 53 | eq(Restaurant::cuisine.name, "American"), 54 | eq(Restaurant::borough.name, "Queens") 55 | ) 56 | ) 57 | 58 | collection 59 | .find(queryParams) 60 | .limit(pageSize) 61 | .skip(offset) 62 | .collect { 63 | println(it) 64 | } 65 | } 66 | 67 | suspend fun readWithIndex(database: MongoDatabase) { 68 | val collection = database.getCollection(collectionName = "restaurants") 69 | val options = IndexOptions().apply { 70 | this.name("restaurant_id_index") 71 | this.background(true) 72 | } 73 | 74 | collection.createIndex( 75 | keys = Indexes.ascending("restaurant_id"), 76 | options = options 77 | ) 78 | 79 | val filters = Filters.gte("restaurant_id", "40000000") 80 | val sort = Sorts.ascending("restaurant_id") 81 | 82 | collection 83 | .find(filter = filters) 84 | .sort(sort = sort) 85 | .limit(200) 86 | .hintString("restaurant_id_index") 87 | .collect { 88 | println(it) 89 | } 90 | } 91 | 92 | 93 | 94 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /src/main/kotlin/Setup.kt: -------------------------------------------------------------------------------- 1 | import com.mongodb.MongoException 2 | import com.mongodb.kotlin.client.coroutine.MongoClient 3 | import com.mongodb.kotlin.client.coroutine.MongoDatabase 4 | import kotlinx.coroutines.flow.count 5 | import kotlinx.coroutines.runBlocking 6 | import org.bson.BsonInt64 7 | import org.bson.Document 8 | import java.util.* 9 | 10 | fun main() { 11 | val databaseName = "sample_restaurants" 12 | 13 | runBlocking { 14 | 15 | val database = setupConnection(databaseName = databaseName, "MONGODB_URI") 16 | 17 | if (database != null) { 18 | listAllCollection(database = database) 19 | 20 | dropCollection(database = database) 21 | } 22 | } 23 | } 24 | 25 | suspend fun setupConnection( 26 | databaseName: String = "sample_restaurants", 27 | connectionEnvVariable: String = "MONGODB_URI" 28 | ): MongoDatabase? { 29 | val connectString = if (System.getenv(connectionEnvVariable) != null) { 30 | System.getenv(connectionEnvVariable) 31 | } else { 32 | // Not a good practice only for demo purpose. 33 | "mongodb+srv://:@cluster0.sq3aiau.mongodb.net/?retryWrites=true&w=majority" 34 | } 35 | 36 | val client = MongoClient.create(connectionString = connectString) 37 | val database = client.getDatabase(databaseName = databaseName) 38 | 39 | return try { 40 | // Send a ping to confirm a successful connection 41 | val command = Document("ping", BsonInt64(1)) 42 | database.runCommand(command) 43 | println("Pinged your deployment. You successfully connected to MongoDB!") 44 | database 45 | } catch (me: MongoException) { 46 | System.err.println(me) 47 | null 48 | } 49 | } 50 | 51 | suspend fun listAllCollection(database: MongoDatabase) { 52 | 53 | val count = database.listCollectionNames().count() 54 | println("Collection count $count") 55 | 56 | print("Collection in this database are ---------------> ") 57 | database.listCollectionNames().collect { print(" $it") } 58 | println() 59 | } 60 | 61 | suspend fun dropCollection(database: MongoDatabase) { 62 | database.getCollection(collectionName = "collectionName").drop() 63 | } 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /src/main/kotlin/Update.kt: -------------------------------------------------------------------------------- 1 | import com.mongodb.client.model.Filters 2 | import com.mongodb.client.model.Updates 3 | import com.mongodb.kotlin.client.coroutine.MongoDatabase 4 | import kotlinx.coroutines.runBlocking 5 | import kotlin.random.Random 6 | 7 | fun main() { 8 | 9 | runBlocking { 10 | setupConnection()?.let { db: MongoDatabase -> 11 | updateSingleDocument(db) 12 | updateMultipleDocuments(db) 13 | } 14 | } 15 | } 16 | 17 | 18 | suspend fun updateSingleDocument(db: MongoDatabase) { 19 | val collection = db.getCollection("restaurants") 20 | val queryParam = Filters.eq("restaurant_id", "restaurantId") 21 | val updateParams = Updates.set("restaurant_id", Random.nextInt().toString()) 22 | collection.updateOne(filter = queryParam, update = updateParams).also { 23 | println("Total docs matched ${it.matchedCount} and modified ${it.modifiedCount}") 24 | } 25 | } 26 | 27 | suspend fun updateMultipleDocuments(db: MongoDatabase) { 28 | val collection = db.getCollection("restaurants") 29 | val queryParam = Filters.eq(Restaurant::cuisine.name, "Chinese") 30 | val updateParams = Updates.combine( 31 | Updates.set(Restaurant::cuisine.name, "Indian"), 32 | Updates.set(Restaurant::borough.name, "Brooklyn") 33 | ) 34 | 35 | collection.updateMany(filter = queryParam, update = updateParams).also { 36 | println("Total docs matched ${it.matchedCount} and modified ${it.modifiedCount}") 37 | } 38 | } 39 | --------------------------------------------------------------------------------