Title: mongodb command with sort and limit
Tags: java;mongodb
Question: 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!

Here is the accepted answer: 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();
Comment for this answer: Im getting (Cursor id=0, ns=user.system.profile, query={ "millis" : 1}, fields={ "$natural" : -1}, numIterated=0, limit=1, addr=localhost:27017, readPreference=ReadPreference.PRIMARY) any ideas? thanks!
Comment for this answer: Yes the update does represent my current code. I don't have access to that specific method for some reason so i was trying another way. Ill try find out why i don't have it. Thanks!
Comment for this answer: Should your edit represent your current code? Then please read carefully my given answer: The function to call is **findOne(…)** instead of _find(…)_, the return value is a **DBObject** instead of a _DBCursor_ and the first parameter should be an **empty** _DBObject_ since it represents the query. Please copy and paste my code and try again.
Comment for this answer: The method is available since version 2.9.0 - any chance to upgrade? Otherwise I think you have to go with your first approach.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:02/20/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><mongodb>', 'Title': 'mongodb command with sort and limit', 'ViewCount': 1911, 'id': 14989723, 'user_AboutMe': '', 'user_AccountId': 2261835.0, 'user_DisplayName': 'edited', 'user_Reputation': 73.0, 'user_Views': 32.0, 'user_id': 1991717.0}}