edited
edited

Reputation: 73

mongodb command with sort and limit

Hi i am trying to implement this exact command below using the Mongo Java api

db.system.profile.find({},{millis:1}).sort({$natural:-1}).limit(1);

I was thinking of doing something like below, but i am only expecting a single INT to be returned and this may be a wrong/long way of doing it.

Mongo mongoClient = new Mongo( "localhost" , 27017 );
        DB db = mongoClient.getDB( "user" );    
        /*  db.system.profile.find({},{millis:1}).sort({$natural:-1}).limit(1);*/
        DBCollection collTime = db.getCollection("system.profile");
        DBCursor cursor = collTime.find(new BasicDBObject("millis", 1),new BasicDBObject("$natural", -1)).limit(1);  
        System.out.println(cursor.toString());

Any help would be great!

Upvotes: 2

Views: 1977

Answers (1)

nutlike
nutlike

Reputation: 4975

Have a look at public DBObject findOne(DBObject o, DBObject fields, DBObject orderBy). Code would look something like this:

String str = collection.findOne(new BasicDBObject(), new BasicDBObject("millis", 1),
    new BasicDBObject("$natural", -1)).get("millis").toString();

Upvotes: 4

Related Questions