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);
}
Related videos on Youtube
jaffer_syed
Updated on June 04, 2022Comments
-
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 almost 4 yearsHello where does the
client
variable come from when you are usingMongoDatabase database = client.getDatabase("test");
? -
jaffer_syed almost 4 yearsThis is located in the second code block in the
getDocument()
method -
jaffer_syed almost 4 yearsAlso how do you use the Autowired
MongoClient
in a public static method ? -
prasad_ almost 4 yearsPlease 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 almost 4 yearsI'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_ almost 4 yearsHave you defined the
MyRepository
? -
prasad_ almost 4 years@alienCY You need the
Test3
POJO class, theMyRepository
interface, theMongoClientConfiguration
classes. Then, implement theCommandLineRunner
interface (can do from the Spring Boot Application's class) - and call thegetCollectionObjects()
from the implementedrun
method. Note this is for the (3) example.