Typically, you perform low-level access using the MongoTemplate
execute(β¦)
methods, which accept callbacks giving you access to the Mongo source API.
class MyClient { private final MongoOperations operations; @Autowired public MyClient(MongoOperations mongoOperations) { this.operations = operations; } void yourMethod() { operations.execute(new CollectionCallback<YourDomainClass>() { YourDomainClass doInCollection(DBCollection collection) {
The advantage of this template approach is that a MongoTemplate
instance that supports the MongoOperations
interface will still take care of all resource management and exception DataAccessException
(converting all Mongo specific exceptions to the Spring DataAccessException
hierarchy).
However, for your specific example, you can simply go straight ahead and do the following:
Query query = new Query().with(new Sort(DESC, "$natural")).limit(1); DBObject result = operations.find(query, DBObject.class, "oplog.$main");
Here you can mix and match the type that you pass to the find(β¦)
method so that the template can transform the result into a Map
object or domain object, if necessary. As stated above, you also get resource management and translation of exceptions that are not in your sample code.
source share