Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Franck Avatar asked Dec 21 '12 16:12

Franck


People also ask

Does MongoDB support sorting?

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.

What is the use of sort () in MongoDB?

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.

How does MongoDB limit work?

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.


2 Answers

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);
like image 175
JohnnyHK Avatar answered Oct 19 '22 19:10

JohnnyHK


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());
}
like image 4
Joel Mata Avatar answered Oct 19 '22 18:10

Joel Mata