Create the following folder structure:

pom.xml: (if using Gradle, replace pom.xml with build.gradle)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.maxjava</groupId> <artifactId>SpringRESTAPIMongoTemplate</artifactId> <version>1.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>6.1.6</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>4.3.0</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>5.0.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.4</version> </dependency> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <version>3.0.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.13.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>
plugins { id 'java' id 'war' } java { sourceCompatibility = 17 targetCompatibility = 17 } group 'net.maxjava' version '1.0' repositories { mavenCentral() } dependencies { implementation group: 'org.springframework', name: 'spring-webmvc', version: '6.1.6' implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.15.4' implementation group: 'org.springframework.data', name: 'spring-data-mongodb', version: '4.3.0' implementation group: 'org.mongodb', name: 'mongodb-driver-sync', version: '5.0.1' implementation group: 'jakarta.annotation', name: 'jakarta.annotation-api', version: '3.0.0' compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.30' annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.30' }
Some notes about pom.xml:
- spring-webmvc for necessary Spring REST controllers and its dependencies
- jackson-databind is for the java object serialization and deserialization
- spring-data-mongodb for using Spring MongoTemplate and other Spring Data MongoDB libraries
- mongodb-driver-sync for connection to MongoDB
- jakarta.annotation-api is needed for annotations like @PostConstruct
- lombok to remove boilerplate code like get and set
- maven-compiler-plugin is for compiling the code using source version 17 and target version 17
- A war artifact will be created for deployment to servlet containers
Some notes about build.gradle:
- spring-webmvc for necessary Spring REST controllers and its dependencies
- jackson-databind is for the java object serialization and deserialization
- spring-data-mongodb for using Spring MongoTemplate and other Spring Data MongoDB libraries
- mongodb-driver-sync for connection to MongoDB
- jakarta.annotation-api is needed for annotations like @PostConstruct
- lombok to remove boilerplate code like get and set
- sourceCompatibility and targetCompatibility is for compiling the code using source version 17 and target version 17
- A war artifact will be created for deployment to servlet containers
web.xml:
<web-app> <display-name>Spring REST API using MongoTemplate</display-name> <servlet> <servlet-name>SpringRESTAPIMongoTemplate</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myApplicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringRESTAPIMongoTemplate</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
Some notes about web.xml:
- org.springframework.web.servlet.DispatcherServlet is the servlet class for Spring
- /WEB-INF/myApplicationContext.xml is the location of the Spring context configuration file
myApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="controller,repository"/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven> </beans>
Some notes about myApplicationContext.xml:
- <context:component-scan base-package="controller,repository"/> is for Spring to look for classes in specific packages to create beans
- <mvc:message-converters> is to specify library for json serialization and deserialization
This tutorial based on the Mongo DB having a database "mydb" with an user "myuser" and password "mypassword" having the "readWrite" role. The user could be created by:
db.createUser( { user: "myuser", pwd: "mypassword", roles: [ { role: "readWrite", db: "mydb" } ] });
Create a collection "mycollection" if not exists:
db.createCollection("mycollection");
and the index:
db.mycollection.createIndex({"lastName":1});
MyController.java:
package controller; import repository.MongoDBRepository; import model.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/myapp") public class MyController { @Autowired MongoDBRepository mongodbRepository; @PostMapping("/customer") public void insertCustomer(@RequestBody Customer customer) { mongodbRepository.insertCustomer(customer); } @GetMapping("/customer") public List<Customer> getCustomerByLastName(@RequestParam("lastName") String lastName) { List<Customer> customerList = mongodbRepository.getCustomerByLastName(lastName); return customerList; } @PutMapping("/customer") public void updateCustomerByLastName(@RequestBody Customer customer) { mongodbRepository.updateCustomerByLastName(customer); } @DeleteMapping("/customer") public void deleteCustomerByLastName(@RequestParam("lastName") String lastName) { mongodbRepository.deleteCustomerByLastName(lastName); } }
Some notes about MyController.java:
- This is Spring REST API which putting @RestController will do the trick (and make sure the package of this class got scanned in bean creation)
- Autowires MongoDBRepository which is the bean to interact with the database.
- This class provides insertCustomer, updateCustomerByLastName, getCustomerByLastName and deleteCustomerByLastName functions to show some basic operations on data
Customer.java:
package model; import lombok.Data; @Data public class Customer { private String _id; private String lastName; private String firstName; private Address address; private String phone; private String email; }
Some notes about Customer.java:
- This is the object used in the request body and response body of the REST APIs
Address.java:
package model; import lombok.Data; @Data public class Address { private String street; private String city; private String state; private Integer zipCode; }
Some notes about Address.java:
- This is used in the Customer class
MongoDBRepository.java:
package repository; import com.mongodb.ConnectionString; import model.Customer; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; import jakarta.annotation.PostConstruct; import java.util.List; @Repository public class MongoDBRepository { private MongoTemplate mongoTemplate; @PostConstruct public void init() { ConnectionString connectionString = new ConnectionString("mongodb://myuser:mypassword@localhost:27017/mydb?connectTimeoutMS=5000&serverSelectionTimeoutMS=20000"); MongoDatabaseFactory mongoDbFactory = new SimpleMongoClientDatabaseFactory(connectionString); mongoTemplate = new MongoTemplate(mongoDbFactory); } public void insertCustomer(Customer customer) { mongoTemplate.insert(customer, "mycollection"); } public ListgetCustomerByLastName(String lastName) { List customerList = mongoTemplate.find(Query.query(Criteria.where("lastName").is(lastName)), Customer.class, "mycollection"); return customerList; } public void updateCustomerByLastName(Customer customer) { Update update = new Update(); if (customer.getFirstName() != null) { update.set("firstName", customer.getFirstName()); } if (customer.getLastName() != null) { update.set("lastName", customer.getLastName()); } if (customer.getEmail() != null) { update.set("email", customer.getEmail()); } if (customer.getPhone() != null) { update.set("phone", customer.getPhone()); } if (customer.getAddress() != null) { update.set("address", customer.getAddress()); } mongoTemplate.updateMulti(Query.query(Criteria.where("lastName").is(customer.getLastName())), update, "mycollection"); } public void deleteCustomerByLastName(String lastName) { mongoTemplate.remove(Query.query(Criteria.where("lastName").is(lastName)), "mycollection"); } }
Some notes about MongoDBRepository.java:
- @Repository to specify the class as Spring bean
- @PostConstruct to specify init() to run when the class is initiated, which is to create the MongoDatabaseFactor and MongoTemplate object
- MongoTemplate is a thread-safe object which can make the MongoDBRepository bean sharable across multiple concurrent requests
- This class supports insertCustomer, updateCustomerByLastName, getCustomerByLastName and deleteCustomerByLastName
- Assume MongoDB is at localhost 27017, otherwise please use corresponding values
Sample requests and responses(assume the war file is deployed to <CONTEXT_PATH>):
- Add a new record:
curl --request POST '<CONTEXT_PATH>/myapp/customer' --header 'Content-Type: application/json' --data-raw ' { "lastName": "Smith", "firstName": "Ethan", "email": "ethan.smith@maxjava.net", "phone": "650-123-1234", "address": { "street": "54321 Doyle Rd", "city": "Lexington", "state": "KY", "zipCode": 56789 } }'
- Retrieve the record by last name
Response:curl --request GET '<CONTEXT_PATH>/myapp/customer?lastName=Smith'[ { "_id": "62ad3907b7a6aa67e211fc12", "lastName": "Smith", "firstName": "Ethan", "address": { "street": "54321 Doyle Rd", "city": "Lexington", "state": "KY", "zipCode": 56789 }, "phone": "650-123-1234", "email": "ethan.smith@maxjava.net" } ] - Retrieve the record by last name
curl --request PUT '<CONTEXT_PATH>/myapp/customer' --header 'Content-Type: application/json' --data-raw '{ "lastName": "Smith", "phone": "669-123-1234" }'
- Retrieve the record by same last name again
Response:curl --request GET '<CONTEXT_PATH>/myapp/customer?lastName=Smith'[ { "_id": "62ad3907b7a6aa67e211fc12", "lastName": "Smith", "firstName": "Ethan", "address": { "street": "54321 Doyle Rd", "city": "Lexington", "state": "KY", "zipCode": 56789 }, "phone": "669-123-1234", "email": "ethan.smith@maxjava.net" } ] - Deleting records by the last name
curl --request DELETE '<CONTEXT_PATH>/myapp/customer?lastName=Smith'
- Retrieve the record by same last name again
Response:curl --request GET '<CONTEXT_PATH>/myapp/customer?lastName=Smith'[]