How to Find highest value in mongodb using java

3,931 views
Skip to first unread message

prem kumar

unread,
Nov 2, 2012, 4:25:02 AM11/2/12
to mongod...@googlegroups.com
Hi,

        How do I find highest value in mongodb using java.

For example :

         
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 1}
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 2}
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 5}
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 3}
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 4}
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 9}
{ "_id" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 6}

This example value for the number is 1,2,5,3,4,9,6...
How to find highest value in this example using java.


Thanks,
Prem


Sam Millman

unread,
Nov 2, 2012, 5:24:50 AM11/2/12
to mongod...@googlegroups.com
I am a little rusty in Java however in the console (which should be asily translateable):

db.col.find().sort({number: -1}).limit(1)

Will find the highest number in that group.




--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

prem kumar

unread,
Nov 2, 2012, 5:36:09 AM11/2/12
to mongod...@googlegroups.com
Hi,

        Thanks for Your reply.
         I know that query. How can I write in java that is find the highest value?

Louisa Berger

unread,
Nov 2, 2012, 10:47:42 AM11/2/12
to mongod...@googlegroups.com
To translate that command into the Java driver : 

coll.find().sort( new BasicDBObject( "number" , -1 ) ).limit(1);

Himanshu Joshi

unread,
Sep 9, 2013, 3:39:16 AM9/9/13
to mongod...@googlegroups.com
Hi,

This query gives the output in the form :

{ "FieldName" : value}

Is there any way to get single value only as a output, so that it can be assigned to a variable or returned etc.

Sam Millman

unread,
Sep 9, 2013, 5:58:32 AM9/9/13
to mongod...@googlegroups.com
There is no way to change that and most likely there won't be. I guess there could be a clause within the driver to extract singular fields and apply them to the symbol table, however, I would imagine it is also easy enough to just do within your app.


--
--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb
 
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages