How to Insert MongoDB Document using Spring Data Part 2

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

This is part two in a tutorial series explaining how to insert MongoDB document using Spring data. Part one of this series focused on how to configure a project using the online tool ‘Spring Initializr’ for creating a Spring project. Part one also covered managed Java classes that are handled by the application server as the classes are created.

Prerequisites

  • A through comprehension of the first part of this tutorial series, understanding how to setup the Spring project and the classes that will be expanded on in this part of the tutorial series.

Configuring Srping Data MongoDB Annotations

First, the Java domain used in this tutorial must be configured in order to insert MongoDB document using Spring data.

Modify the Product.java class by appending some of the annotations with the following command:

1
2
3
4
5
6
package com.appspring;

import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "Product")
public class Product {
  • The @Document annotation is used to mark this Java class as the document of the MongoDB collection with this code: @Document(collection = "Product"), in this case our collection will named Product.

Creating a Spring Data MongoDB Repository.

This section will create the MongoRepository that enables access with its CRUD methods, specially the insert() method.

  • First, instead of creating a class, create a new Java interface and name it ‘ProductController’.

  • Now execute the following code.

1
2
3
4
5
6
7
8
9
package com.appspring;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductRepository extends MongoRepository-Product, String- {

}
  • This java interface will be extending the MongoRepository-Product, String-. This requires two types for its parameter; the first is the Product.java with the type of the field being a string.

  • The @Repository annotation is used for this Java class as the application’s repository.

Creating a MongoDB Sample Dataset.

A sample dataset will be created for demo purposes. This Java class will serve as a database seeder that will populate the MongoDB database with a configured MongoDB collection.

  • Create a new Java class and name it Db.java. Now run the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.appspring;

import java.util.Arrays;
import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class Db implements  CommandLineRunner {


    private ProductRepository productRepository;

    public Db(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @Override
    public void run(String... args) throws Exception {

        Product p1 = new Product(

                "111445GB3",
                "Simsong One mobile phone",
                "The greatest Onedroid phone on the market",
                new ManDetails("A123X","A123Y"),
                new ShipDetails (350, 10, 10, 1),
                99,
                100
        );
        Product p2 = new Product(

                "111445y54",
                "Noko mobile phone",
                "The greatest Onedroid phone on the market",
                new ManDetails("A123X","A123Y"),
                new ShipDetails (350, 10, 10, 1),
                99,
                100
        );
        // drop all database first
        this.productRepository.deleteAll();

        // save all the specified product
        List<Product> product = Arrays.asList(p1,p2);
        this.productRepository.saveAll(product);
    }
}

Following is a breakdown of the above code:

  • This class will be implementing the CommandLineRunner that tells the application to run the functions that will be created once the spring data is initiated.
  • By using the @Component annotation, the application is instructed to treat this Java class as a bean.
  • Note that the above code will erase all data that is present and then save the specified product every time the application is ran. This is designed to save time for testing purposes.

Creating the Java Controller Class

This section will cover how to create the controller class of the application. This is for handling the request from the user.

  • First, create the file by using the same steps used for creating a Java class and then run the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.appspring;

import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
public class ProductController {

    private ProductRepository productRepository;

    public ProductController(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    // gets all record
    @GetMapping
    public List<Product> getAll(){
        List<Product> resorts = this.productRepository.findAll();

        return resorts;
    }


}
  • The annotations used in the above codes were the REST VERBS that maps the required operation to there respective annotations.

Configuring MongoDB Database Connection

This section will cover the basics on how to connect to a MongoDB database instance using the application.properties file.

Execute the following code to connect to a MongoDB database instance:

1
2
3
4
5
6
// localhost for the host
spring.data.mongodb.host=localhost
// mongodb port
spring.data.mongodb.port=27017
// the name of our database
spring.data.mongodb.database=ProdcutDb

Now test the application by simply clicking the ECLIPSE “Run” button.

To verify the application is able to insert the documents that were configured earlier, execute the following code in the Mongo shell:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
> db.Product.find().pretty();
{
        "_id" : ObjectId("5defa3f77528430b233d6285"),
        "sku" : "111445GB3",
        "title" : "Simsong One mobile phone",
        "description" : "The greatest Onedroid phone on the market",
        "manDetails" : {
                "modelNumber" : "A123X",
                "partNumber" : "A123Y"
        },
        "shipDetails" : {
                "weight" : 350,
                "width" : 10,
                "height" : 10,
                "depth" : 1
        },
        "quantity" : 99,
        "price" : 100,
        "_class" : "com.appspring.Product"
}
{
        "_id" : ObjectId("5defa3f77528430b233d6286"),
        "sku" : "111445y54",
        "title" : "Noko mobile phone",
        "description" : "The greatest Onedroid phone on the market",
        "manDetails" : {
                "modelNumber" : "A123X",
                "partNumber" : "A123Y"
        },
        "shipDetails" : {
                "weight" : 350,
                "width" : 10,
                "height" : 10,
                "depth" : 1
        },
        "quantity" : 99,
        "price" : 100,
        "_class" : "com.appspring.Product"
}
>

Inserting a Record in MongoDB

With the application now properly configured, the surprisingly straightforward and short insert function can be coded.

Append the following code in the ProductController.java:

1
2
3
4
5
@PutMapping("/insert")
    public void insert(@RequestBody Product product) {

        this.productRepository.insert(product);
    }

Alternatively, the test can also be performed using the Postman application shown here:

-img src=”https://i.gyazo.com/f8f1e5556d525765bd4a4e901566d412.gif” width=”632″ height=”456″-

The insert function can also be verified via the Mongo shell as shown here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
> db.Product.find().pretty();
{
        "_id" : ObjectId("5defa3f77528430b233d6285"),
        "sku" : "111445GB3",
        "title" : "Simsong One mobile phone",
        "description" : "The greatest Onedroid phone on the market",
        "manDetails" : {
                "modelNumber" : "A123X",
                "partNumber" : "A123Y"
        },
        "shipDetails" : {
                "weight" : 350,
                "width" : 10,
                "height" : 10,
                "depth" : 1
        },
        "quantity" : 99,
        "price" : 100,
        "_class" : "com.appspring.Product"
}
{
        "_id" : ObjectId("5defa3f77528430b233d6286"),
        "sku" : "111445y54",
        "title" : "Noko mobile phone",
        "description" : "The greatest Onedroid phone on the market",
        "manDetails" : {
                "modelNumber" : "A123X",
                "partNumber" : "A123Y"
        },
        "shipDetails" : {
                "weight" : 350,
                "width" : 10,
                "height" : 10,
                "depth" : 1
        },
        "quantity" : 99,
        "price" : 100,
        "_class" : "com.appspring.Product"
}
{
        "_id" : ObjectId("5defa4f67528430b233d6287"),
        "sku" : "111445HC3",
        "title" : "Huwaw One mobile phone",
        "description" : "The greatest Onedroid phone on the market",
        "manDetails" : {
                "modelNumber" : "A123X",
                "partNumber" : "A123Y"
        },
        "shipDetails" : {
                "weight" : 350,
                "width" : 10,
                "height" : 10,
                "depth" : 1
        },
        "quantity" : 99,
        "price" : 100,
        "_class" : "com.appspring.Product"
}
>

As illustrated, the new document was successfully inserted with a sku value of 111445HC3, as compared to the above gif. file.

Conclusion

This was part two in a tutorial series explaining how to insert MongoDB document using Spring data. This part of the tutorial series explained how to configure Spring data for MongoDB annotations, create a Spring data MongoDB repository, a MongoDB sample dataset, the Java controller class and how to configure the MongoDB database connection. This tutorial also covered how to insert a record in MongoDB and test the application. Remember that the insert function can be verified in multiple ways, including with the Postman application and via the Mongo shell.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.