Franck
Franck

Reputation: 1764

mongodb issue in java with limit and sort

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?

Upvotes: 14

Views: 38687

Answers (4)

Vinayak Mahadev
Vinayak Mahadev

Reputation: 1

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

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311975

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

Upvotes: 27

Joel Mata
Joel Mata

Reputation: 514

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

Upvotes: 5

Aman Goel
Aman Goel

Reputation: 3551

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.

Upvotes: 0

Related Questions