Collection:progs
{ "_id" : "ABC", "defaultDirectory" : "abc", "defaultRecvDirectory" : "abc" }
{ "_id" : "RAS", "defaultRecvDirectory" : "recv/ras" }
{ "_id" : "SND", "defaultSendDirectory" : "send/snd" }
In the mongo console:
db.progs.find({"_id":{"$lt":"ZZZZZZZZZ"}}).sort({"_id":-1}).limit(1);
==> { "_id" : "SND", "defaultSendDirectory" : "send/snd" }
In Java:
BasicDBObject query = new BasicDBObject();
query.put("_id", new BasicDBObject("$lt", "ZZZZZZZZZZ"));
DBCursor cursor = collection.find(query).sort(new BasicDBObject("_id","-1")).limit(1);
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
==> { "_id" : "ABC", "defaultSendDirectory" : "abc", "defaultRecvDirectory" : "abc" }
Someone can explain the difference?
Sort and Index UseMongoDB can obtain the results of a sort operation from an index which includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.
MongoDB – sort() Method The sort() method specifies the order in which the query returns the matching documents from the given collection. You must apply this method to the cursor before retrieving any documents from the database.
The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.
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);
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With