Kotlin – SpringBoot MongoDB – Model One-to-One, One-to-Many Relationships Embedded Documents

With MongoDB, we can structure related data by embedded documents. In general, embedding gives a better performance for read operations. So in the tutorial, JavaSampleApproach will show you way to work with Embedded Documents using SpringBoot by Kotlin language.

I. Technologies

– Kotlin 1.2.20
– Apache Maven 3.5.2
– Spring Tool Suite – Version 3.9.0.RELEASE
– Spring Boot – 1.5.10.RELEASE
– MongoDB: v3.4.1

II. MongoDB – Embedded Documents

Embedded Documents are generally known as denormalized models. It is a way to structure related data in a single document. See below diagram:

kotlin mongodb-embedded-document-structure

In general, we decide to design data as embedded models in case: data contains one-to-one or one-to-many relationships between entities.

With embedding data model, in general, it gives us a better performance for read operations. And we can use a single atomic read/write database operation to request and retrieve or update related data.

However, a weakness point is embedding related data in documents may lead to situations where documents grow after creation.

III. Practice

In the tutorial, we use SpringToolSuite to create a Kotlin SpringBoot project for MongoDB embedded documents:

kotlin mongodb-embedded-document-project structure

Step to do
– Create Kotlin SpringBoot project
– Create Document models
– Create MongoRepository
– Implement Client
– Run and check results

1. Create Kotlin SpringBoot project

Using Spring Tool Suite, create a Kotlin SpringBoot project. Then open pom.xml file, add dependencies:

2. Create Document models

Create 3 class models {Company, Product, Contact} with one-to-one relationship between Company & Contact, and one-to-many relationship between >Company & Product in embedded data model structure.

– Company model:

– Contact model:

– Product model:

3. Create MongoRepository

– Open application.properties, add configuration to connect with Mongo Server:

4. Implement Client

Use CommandLineRunner to implement a simple client to manipulate data from MongoDB via CompanyRepository:

5. Run and check results

Start MongoDB server by commandline: .\MongoDB\Server\3.4\bin>mongod.exe

-> Logs:

Run the SpringBoot project with commandline: mvn spring-boot:run

-> Logs:

Run MongoDB shell by commandline: .\MongoDB\Server\3.4\bin>mongo.exe.

-> Logs:

Results with MongoDB shell:

IV. Sourcecode

KotlinSpringMongoDbEmbeddedDocument

By JavaSampleApproach | February 11, 2018.

Related Posts


Got Something To Say:

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

*