Spring Boot and MongoDB example


In this example we will use Spring MongoTemplate to interact with the database.

Add the dependencies

In your pom.xml add the spring-data-mongodb and mongodb-jdbc dependencies.

<dependency> 
  <groupId>org.springframework.data</groupId> 
  <artifactId>spring-data-mongodb</artifactId> 
  <version>3.3.0</version> 
</dependency> 
         
<dependency> 
  <groupId>org.mongodb</groupId> 
  <artifactId>mongodb-jdbc</artifactId> 
  <version>1.0.3</version> 
</dependency> 

Add the Spring Configuration

I suggest to create a new configuration file in your Spring Boot project to add the MongoDB configuration:

import com.mongodb.ConnectionString; 
import com.mongodb.client.MongoClient; 
import com.mongodb.client.MongoClients; 
 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.data.mongodb.core.MongoTemplate; 
 
@Configuration 
public class MongoConfig { 
 
  public @Bean MongoClient mongoClient() { 
 
    MongoClient mongoClient = MongoClients.create( 
      new ConnectionString("mongodb://[USER|admin]:[YOUR_PASSWORD]@[YOURIP]:[PORT:27017]/[database-name] authSource=admin") 
    ); 
 
    return mongoClient; 
  } 
 
  public @Bean MongoTemplate mongoTemplate() { 
    return new MongoTemplate(mongoClient(), "[database-name]"); 
  } 
} 

This example is as simple as possible, the connection parameters are inserted directly in the code. In your project use an external parameter.

In the code we create 2 Spring beans:

  • a MongoClient that is provided by the JDBC driver

    The MongoClient provide a representation of a MongoDB Cluster (standalone, replica, shared cluster). It handles the communication with the database instance.

  • a MongoTemplate provided by Spring Data

    It handles the communication between your Spring code and the MongoClient this class implements the MongoOperations class that can be used for Tests because is easily mocked.

What is the authSource=admin at the end of the JDBC String?

This part of the string is often forgotten generating the following error during the execution:

Servlet.service() for servlet [dispatcherServlet] in context with path []  
threw exception [Request processing failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException:  
Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='[USER_NAME]', source='[DATABASE_NAME]', password=<hidden>, mechanismProperties=<hidden>};  
nested exception is com.mongodb.MongoSecurityException:  
Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='[USER_NAME]', source='[DATABASE_NAME]', password=<hidden>, mechanismProperties=<hidden>}] with root cause 
 
com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server [SERVER_IP]:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"} 
        at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:198) ~[mongodb-driver-core-4.4.0.jar:na] 

The parameter authSource defines where the authorizations are stored (name of the database). You can find the details of the MongoDB connection string here.

How to use the the MongoTemplate

In your code you can reference the MongoTemplateand call the method to read/write the database.

@Service 
public class MyService() {  
   
  @Autowired 
  private MongoTemplate mongoTemplate; 
 
    public void writeToDatabase(Comment comment) { 
        mongoTemplate.save(comment);  
    } 

The list of available operations you can do with MongoTemplate is pretty long. You should check the documentation / list of available methods.



marco.dev newsletter

Be the coolest developer in your team joining our community!
WebApp built by Marco using SpringBoot, Java 16, Mustache, Markdown and Hosted using Jelastic