Description
DBCursor.limit(10) is a simple API that allows the user to get the first 10 (or no more than 10) documents back from the DB.
However there does not seem to be a simple method to get the last 10 rows.
Normally (in SQL land) you would do something like DBCursor.limit(-10) to fetch the last 10 documents, however it appears this is currently used to support backwards compatibility with some old behavior.
Perhaps a new API like DBCursor.last(10) could be introduced for this?
Currently the user needs to code something like the following to get the last 10 documents from a query:
|
|
final MongoClient mongoClient = new MongoClient(MONGODB_HOST, MONGODB_PORT);
|
final String dbName = "myDB";
|
final DB db = mongoClient.getDB(dbName);
|
final DBCollection dbCollection = db.getCollection("myCollection");
|
final DBCursor dbCursor = dbCollection.find(/* query DBObject here */);
|
int length = dbCursor.count();
|
|
// to get the last 10 we need to skip length - 10 (or skip none if length <= 10)
|
final int skip = Math.max(0, length - 10);
|
if (skip > 0) {
|
dbCursor.skip(skip);
|
length = 10;
|
}
|
|
while (dbCursor.hasNext()) {
|
DBObject dbObject = dbCursor.next();
|
System.out.println(dbObject);
|
}
|
|
// Clean up resources:
|
dbCursor.close();
|
mongoClient.close();
|