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

10,713

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);
}
Share:
10,713

Related videos on Youtube

jaffer_syed
Author by

jaffer_syed

Updated on June 04, 2022

Comments

  • jaffer_syed
    jaffer_syed almost 2 years

    Hello I am trying to export the MongoClient after a successful connection in Spring Boot and I am trying to use it in other files so that I do not have to call the connection every single time that I need to make changes in my MongoDB database.

    The connection is pretty simple but the goal would be to connect the application to my database once and then use it wherever I want by importing it in any Java file.

    Thank you

  • jaffer_syed
    jaffer_syed almost 4 years
    Hello where does the client variable come from when you are using MongoDatabase database = client.getDatabase("test"); ?
  • jaffer_syed
    jaffer_syed almost 4 years
    This is located in the second code block in the getDocument() method
  • jaffer_syed
    jaffer_syed almost 4 years
    Also how do you use the Autowired MongoClient in a public static method ?
  • prasad_
    prasad_ almost 4 years
    Please try searching for: "spring boot how to use the Autowired (MongoClient) in a public static method" . You will find quite a few answers - depends upon your need.
  • alienCY
    alienCY almost 4 years
    I've been struggling with the 3rd method for hours and it still says that there is no bean for my repository. Can you help me please? Where shall I declare the @Bean? I'm using java configuration.
  • prasad_
    prasad_ almost 4 years
    Have you defined the MyRepository?
  • prasad_
    prasad_ almost 4 years
    @alienCY You need the Test3 POJO class, the MyRepository interface, the MongoClientConfiguration classes. Then, implement the CommandLineRunner interface (can do from the Spring Boot Application's class) - and call the getCollectionObjects() from the implemented run method. Note this is for the (3) example.