我正在使用 Spring Data MongoDB。但我不想将结果映射到域类。另外,我想在少数情况下访问低级 MongoAB API。但我希望 spring 来管理连接池等。
我如何获取com.mongodb.MongoClient
的实例来执行低级操作。
这是我正在尝试做的事情:
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);
或者我只是想要一个 JSON 对象/DBCursor/DBObject。
最佳答案
你可以这样做
@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);
哪里
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
您的配置文件应包含以下信息:
<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>
这样做,spring 应该继续管理你的连接池。
关于spring - 如何将低级驱动程序 API 与 Spring Data MongoDB 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18683182/