Computer scienceBackendSpring BootSpring DataMongoDB

Using MongoDB with Spring Data

6 minutes read

Spring Data MongoDB offers a single method for configuring operations with various data stores, including relational and non-SQL databases such as MongoDB. MongoDB is a widely used non-SQL database known for its high performance, availability, and scalability. In this topic, you will learn how to set up a Spring Boot project with MongoDB.

Adding MongoDB in a project

To incorporate MongoDB into a Spring Boot project, you need to include the Spring Boot MongoDB starter dependency in the project build file.

If you're using Maven as the build tool, include the following dependency in your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

In Gradle, include the following line in the build.gradle file:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
}

This will integrate the suitable MongoDB driver and Spring Data beans into the project.

Connection string

To configure a connection to a MongoDB instance, you can input necessary settings into the application.properties file. One method is to specify the correct connection string or the URI where MongoDB is operating. The connection string must include the hostname or IP address and the port number in this format:

mongodb://host:port

For example, if MongoDB is operating locally, the connection string would be mongodb://localhost:27017. Additionally, the connection string can include the username, password, database name, and added parameters:

mongodb://username:password@host:port/database?param1=value1&param2=value2...

To tell Spring what connection string to use in connecting MongoDB, you should add the spring.data.mongodb.uri parameter in the application.properties file:

spring.data.mongodb.uri=mongodb://user123:secret@localhost:27017/sandbox

In this example, Spring Data will set its MongoDB client to connect with the username user123 and the password secret to a MongoDB instance running on the local machine, exposing the port 27017, and use the database named sandbox. Replace the username, password, and database with your actual MongoDB username, password, and database name, respectively. If you're operating a local instance of MongoDB without enabled authentication, skip the username and password.

Application properties

Alternatively, you can state individual spring.data.mongodb properties for a more explicit and easy-to-read configuration. This includes properties like host, port, database name, username, password, and the authentication database. Let's examine each of these properties:

  • spring.data.mongodb.host This parameter specifies the host where your MongoDB server is functioning. If you're operating MongoDB on your local machine, set this to localhost. For example:

    spring.data.mongodb.host=localhost
  • spring.data.mongodb.port This parameter pinpoints the port number your MongoDB server is using. The default MongoDB port is 27017. For example:

    spring.data.mongodb.port=27017
  • spring.data.mongodb.database This property indicates the name of the MongoDB database to which your application should connect. For example, if your database is named mydatabase, you should input:

    spring.data.mongodb.database=mydatabase
  • spring.data.mongodb.username This property names the username for MongoDB server authentication. For example:

    spring.data.mongodb.username=myusername
  • spring.data.mongodb.password This property declares the password for MongoDB server authentication. For example:

    spring.data.mongodb.password=mypassword
  • spring.data.mongodb.authentication-database This property states the name of the database holding the user's credentials. In MongoDB, user credentials reside in a database that could be different from the one your application uses. If you're using the same database for your application data and user credentials, you can set this property to match spring.data.mongodb.database. For example:

    spring.data.mongodb.authentication-database=mydatabase

By stating these properties in your application.properties file, Spring Boot will automatically set a Mongo client that connects to your MongoDB server when your application begins. This simplifies the MongoDB connection process, allowing you to focus on developing your application.

Running the application

Let's assume you are running a local MongoDB server on the default port that doesn't require authentication. In this case, the application.properties file would look like this:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=test

Now if you operate the application, it will begin and connect to the database, outputting a log similar to this:

Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
Finished Spring Data repository scanning in 6 ms. Found 0 MongoDB repository interfaces.
MongoClient with metadata {"driver": {"name": "mongo-java-driver|sync|spring-boot", "version": "4.8.2"} ...

To prove the application successfully connects, you can validate it by executing a query:

@Component
class Runner implements CommandLineRunner {
    private final MongoTemplate mongoTemplate;

    Runner(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void run(String... args) {
        var databaseName = mongoTemplate.getMongoDatabaseFactory().getMongoDatabase().getName();
        System.out.println("Using " + databaseName);
    }
}

When the application begins, it will output:

Using test_db

Conclusion

In this topic, you learned how to use MongoDB with Spring Data. You now understand how to include necessary dependencies into your project, state the connection string, and configure Spring Data properties, including its host, port, username, password, and database.

9 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo