mongodb issue in java with limit and sort
Another version based on MongoTemplate:
public List<?> findLimitedSorted(Query query, Object target, String startFrom) {
query.limit(100);
query.with(new Sort(Sort.Direction.ASC, "<field_name>"));
return getMongoTemplate().find(query, target.getClass());
}
Remove the quotes from the "-1"
in your sort:
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id",-1)).limit(1);
Or use Mongodb ASC/DESC constants from com.mongodb.operation.OrderBy
instead of hardcoding 1 / -1
Example:
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id", OrderBy.DESC.getIntRepresentation())).limit(1);