Search code examples
mongodbmongo-java

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?


Solution

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