MongoDB is an open source NoSQL document database that uses a JSON-like schema instead of traditional relational data-based tables. Spring Boot contains several helpers for working with MongoDB, including the spring-boot-starter-data-mongodb and spring-boot-starter-data-mongodb-reactive starters.
Connecting to a MongoDB database
To access MongoDB databases, you can implement an auto-configurable org.springframework.data.mongodb.MongoDatabaseFactory. By default, the instance will try to connect to the MongoDB server at mongodb://localhost/test. The following example shows how to connect to a MongoDB database:
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final MongoDatabaseFactory mongo;
public MyBean(MongoDatabaseFactory mongo) {
this.mongo = mongo;
}
// ...
public MongoCollection<Document> someMethod() {
MongoDatabase db = this.mongo.getMongoDatabase();
return db.getCollection("users");
}
}
import com.mongodb.client.MongoCollection
import org.bson.Document
import org.springframework.data.mongodb.MongoDatabaseFactory
import org.springframework.stereotype.Component
@Component
class MyBean(private val mongo: MongoDatabaseFactory) {
// ...
fun someMethod(): MongoCollection<Document> {
val db = mongo.mongoDatabase
return db.getCollection("users")
}
}
If a custom MongoClient has been defined, it will be used to auto-configure the appropriate MongoDatabaseFactory.
An auto-configured MongoClient is created using the MongoClientSettings bean. If a custom MongoClientSettings was defined, it will be used as is, and the spring.data.mongodb properties will be ignored. Otherwise, MongoClientSettings will be automatically configured and the properties of spring.data.mongodb will be applied to it. In any case, you can declare one or more MongoClientSettingsBuilderCustomizer beans to fine-tune the MongoClientSettings configuration. Each of them will be called in order through the MongoClientSettings.Builder, which is used to build the MongoClientSettings.
You can set the spring.data.mongodb.uri property to change the URL and add additional parameters to the configuration, such as replica set, as shown in the following example:
spring.data.mongodb.uri=mongodb://user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test
spring:
data:
mongodb:
uri: "mongodb:/ /user:secret@mongo1.example.com:12345,mongo2.example.com:23456/test"
Alternatively, you can specify the connection details with using discrete properties. For example, you can declare the following settings in the application.properties file:
spring.data.mongodb.host=mongoserver.example.com
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
spring.data.mongodb.username=user
spring.data.mongodb.password=secret
spring:
data:
mongodb:
host: "mongoserver.example.com"
port: 27017
database: "test"
username: "user"
password: "secret"
spring.data.mongodb.port is not specified, the default value
27017 is used. You can remove this line from the example shown earlier.
MongoClient bean instead using
MongoDatabaseFactory. If you need complete control over the process of establishing a connection to MongoDB, you can optionally declare your own
MongoDatabaseFactory or
MongoClient bean.
MongoTemplate
Spring Data MongoDB> provides a MongoTemplate class that its structure is very similar to JdbcTemplate from Spring. As with JdbcTemplate, Spring Boot automatically adds a template injection bean to the configuration as follows:
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final MongoTemplate mongoTemplate;
public MyBean(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
// ...
public MongoCollection<Document> someMethod() {
return this.mongoTemplate.getCollection("users");
}
}
import com.mongodb.client.MongoCollection
import org.bson.Document
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.stereotype.Component
@Component
class MyBean(private val mongoTemplate: MongoTemplate) {
// ...
fun someMethod(): MongoCollection<Document> {
return mongoTemplate.getCollection("users")
}
}
Repositories Spring Data MongoDB
Spring Data provides repository support for MongoDB. As with the JPA repositories discussed earlier, the basic principle is that queries are built automatically based on method names.
In fact, both Spring Data JPA and Spring Data MongoDB have the same the same general infrastructure. You can take the JPA example from the previous article and, provided that City is now a MongoDB data class and not a JPA object with the @Entity annotation, it will work exactly like this same as shown in the following example:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
public interface CityRepository extends Repository<City, Long> {
Page<City> findAll(Pageable pageable);
City findByNameAndStateAllIgnoringCase(String name, String state);
}
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.Repository
interface CityRepository :
Repository<City?, Long?> {
fun findAll(pageable: Pageable?): Page<City?>?
fun findByNameAndStateAllIgnoringCase(name: String?, state: String?): City?
}
@EntityScan annotation.
Embedded Mongo system
Spring Boot provides automatic configuration for Embedded Mongo. To use it in your Spring Boot application, add a dependency on de.flapdoodle.embed:de.flapdoodle.embed.mongo and set the spring.mongodb.embedded.version property to according to the version of MongoDB that the application will use in a production environment.
DownloadConfigBuilderCustomizer bean.
The port that Mongo listens on can be added to the configuration by setting the property spring.data.mongodb.port. To use a randomly assigned free port, use a value of 0. MongoClient created with MongoAutoConfiguration is automatically configured to use a randomly assigned port.
If SLF4J is in the classpath, the output data generated by Mongo is automatically routed to a logging manager named org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongo.
You can declare your own IMongodConfig beans and IRuntimeConfig to manage Mongo instance configuration and logging routing. The download configuration can be configured by declaring the DownloadConfigBuilderCustomizer bean.
GO TO FULL VERSION