In this post, we will learn to use a MongoCollection instance for database operations in the Spring Boot application.
We all know that we have a spring boot data repository for MongoDB which has an interface MongoRepository and a class MongoTemplate that is the best way in Spring Boot for database operations.
Though, Spring Boot provides these options for database operation. Sometimes, we need to use MongoCollection instance in Spring Boot which is a native way of connecting MongoDB database in Java.
Configurations in our application.properties
file to connect MongoDB database looks like:
spring.data.mongodb.database=mydatabase
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
// other configuration like username/password
Spring Boot automatically provides an instance of MongoDatabaseFactory
interface for factories creating MongoDatabase instances.
See the example below to initialize MongoDatabaseFactory
.
@Autowired
MongoDatabaseFactory mongoDatabaseFactory;
Now, we can use the mongoDatabaseFactory
instance to initialize the MongoCollection
instance with following code:
MongoCollection<Document> employeesCollection = mongoDbFactory.getMongoDatabase().getCollection("employees");
Make sure to import Document from org.bson
package like:
import org.bson.Document;
The employeesCollection
is an instance of a collection of employees
in the database mydatabase
(You can see in the properties file to know the database name).
Now, we can use employeesCollection
object to do database operations like:
employeeCollection.find();
This will return the iterable object of the Document. Where we can find all the keys as fields and their values available in employees
collection.
Similarly, we can use employeeCollection
for other operations available in MongoDB.
The main objective of this post is to learn to use MongoCollection in Spring Boot to work in a Native way.
Hence, I will write another post for CRUD operation in MongoDB using Java.