Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use low-level driver APIs with Spring Data MongoDB

I am using Spring Data MongoDB. But I don't want to map my result to a domain class. Also, I want to access low level MongoAB APIs in few cases. But I want spring to manage the connections pooling etc.

How can i get an instance of com.mongodb.MongoClient to perform low level operations. Here is what I am trying to do :

MongoClient mongoClient = new MongoClient();
DB local = mongoClient.getDB("local");
DBCollection oplog = local.getCollection("oplog.$main");
DBCursor lastCursor = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1);

Or I simply want a JSON object / DBCursor / DBObject.

like image 782
shrw Avatar asked Sep 08 '13 11:09

shrw


People also ask

Can we use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

How does MongoDB integrate with spring?

It's Easy to Connect MongoDB Atlas with Spring Boot Starter data MongoDB artifactid (the dependency we added while creating the Spring Initializr project) in pom. xml. A property on application. properties file to specify the connection string to a MongoDB cluster.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Why _class is added in MongoDB?

Spring Data MongoDB adds _class in the mongo documents to handle polymorphic behavior of java inheritance.


1 Answers

you can do it this way

@Autowired MongoDbFactory factory;
DB local = factory.getDB("local");
DBCollection oplog = local.getCollection("oplog.$main");
DBCursor lastCursor = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1);

Where

MongoDbFactory is an interface provifed by spring-data-mongo that can obtain a        
com.mongodb.DB object and access allthe functionality of a specific MongoDB database   
instance

your configuration file should contain these informations :

<bean id="mongoFactoryBean"
class="org.springframework.data.mongodb.core.MongoFactoryBean">
    <property name="host" value="127.0.0.1"/>
    <property name="port" value="27017"/>
</bean>

<bean id="mongoDbFactory" 
class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
    <constructor-arg name="mongo" ref="mongoFactoryBean"/>
    <constructor-arg name="databaseName" value="local"/>
</bean>

doing it like that, spring should stay managing your connection pool.

like image 57
Centonni Avatar answered Nov 24 '22 10:11

Centonni