14

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?

Franck
  • 1,754
  • 1
  • 13
  • 14

4 Answers4

27

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);
redochka
  • 12,345
  • 14
  • 66
  • 79
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
5

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());
}
Joel Mata
  • 456
  • 4
  • 8
0

Here is the solution which I found with filters, sorting and limit :

 List<Bson> queryFilters = new ArrayList<>();
    queryFilters.add(Filters.eq(SavedReportEntity.FIELD_USER_ID, userId));

   List<Document> documents = getMongoCollection().find(searchFilter).sort(sort).limit(10).into(new ArrayList<Document>());

you will get the list of Documents now you can play with it according to you.

Aman Goel
  • 3,351
  • 1
  • 21
  • 17
0

Getting DBObjects with sortting order from MongoDB:

List<DBObject> list = new LinkedList<DBObject>();    
    DBCursor cursor = db.getCollection("myCol").find().sort(new BasicDBObject("_id",-1)).limit(collection.find(query).count());
        while(cursur.hasNext){
        list.add(cursur.next());
    }
    if(!list.isEmpty())
        for(DBObject dbo: list){
            System.out.println(dbo);
        }
    else
        System.out.println("List is empty");
Eric Aya
  • 69,473
  • 35
  • 181
  • 253