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?

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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());
}

1 Comment

This is the correct answer. Always sort in your query, not after!
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.

Comments

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");

2 Comments

it would be nice if you add some explanation
Ma che cazzo è?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.