Search code examples
javamongodbsortingmongo-java

How to find the smallest number in a mongo query?


I have the following objects in my mongo db:

{
  "type" : "timetype"
  "time" : "18"
}
{
  "type" : "timetype"
  "time" : "5"
}
{
  "type" : "timetype"
  "time" : "43"
}
{
  "type" : "timetype"
  "time" : "23"
}

And my java code looks like:

BasicDBObject query = new BasicDBObject();
query.put("type", "timetype");

 //I don't know what to put in the (...)
DBCursor cursor = Collection.find(query).sort(...).limit(1);

I would like to find the entry with the smallest time in my mongo database that meets the query parameter but I don't know what to put in sort to make that happen.


Solution

  • Something along the lines of

    Collection.find(query).sort(new BasicDBObject( "time" , 1 )).limit(1);
    

    should work.