How to initialize MongoClient once in Spring Boot and use its methods?

Here are couple of ways of creating an instance of MongoClient, configuring and using it within the Spring Boot application.

(1) Registering a Mongo Instance using Java-based Metadata:

@Configuration
public class AppConfig {
    public @Bean MongoClient mongoClient() {
        return MongoClients.create();
    }
}

Usage from CommandLineRunner‘s run method (all examples are run similarly):

@Autowired 
MongoClient mongoClient;

// Retrieves a document from the "test1" collection and "test" database.
// Note the MongoDB Java Driver API methods are used here.
private void getDocument() {
    MongoDatabase database = client.getDatabase("test");
    MongoCollection<Document> collection = database.getCollection("test1");
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());
}

(2) Configure using AbstractMongoClientConfiguration class and use with MongoOperations:

@Configuration
public class MongoClientConfiguration extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create();
    }

    @Override
    protected String getDatabaseName() {
        return "newDB";
    }
}

Note you can set the database name (newDB) you can connect to. This configuration is used to work with MongoDB database using Spring Data MongoDB APIs: MongoOperations (and its implementation MongoTemplate) and the MongoRepository.

@Autowired 
MongoOperations mongoOps;

// Connects to "newDB" database, and gets a count of all documents in the "test2" collection.
// Uses the MongoOperations interface methods.
private void getCollectionSize() {
    Query query = new Query();
    long n = mongoOps.count(query, "test2");
    System.out.println("Collection size: " + n);
}

(3) Configure using AbstractMongoClientConfiguration class and use with MongoRepository

Using the same configuration MongoClientConfiguration class (above in topic 2), but additionally annotate with @EnableMongoRepositories. In this case we will use MongoRepository interface methods to get collection data as Java objects.

The repository:

@Repository
public interface MyRepository extends MongoRepository<Test3, String> {

}

The Test3.java POJO class representing the test3 collection’s document:

public class Test3 {

    private String id;
    private String fld;

    public Test3() {    
    }

    // Getter and setter methods for the two fields
    // Override 'toString' method
    ...
}

The following method to get documents and print as Java objects:

@Autowired 
MyRepository repository;

// Method to get all the `test3` collection documents as Java objects.
private void getCollectionObjects() {
    List<Test3> list = repository.findAll();
    list.forEach(System.out::println);
}

Leave a Comment