2

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!

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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!
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.
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!
The method is available since version 2.9.0 - any chance to upgrade? Otherwise I think you have to go with your first approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.