简体   繁体   中英

How to sort integers in mongodb with java driver?

I've connected mongo database with java and i already have data inside the database. the data in the database looks like this:

{"id":"4654654", "money":"54"}
{"id":"44234654", "money":"102"}
{"id":"123654", "money":"36"}
{"id":"98764654", "money":"5400"}
{"id":"456655", "money":"520"}
{"id":"7654", "money":"789"}
{"id":"3456546", "money":"85"}
{"id":"0346575", "money":"42"}
{"id":"46554645", "money":"2000"}

In java i want to sort the data by "money". so i write this code:

DBCursor cursor = collection.find().sort(new BasicDBOject("money", 1));

while(cursor.hasNext(){
System.out.println(cursor.next().get("money"));
}

I expect that i would get something like this:

36
42
54
85
102
......

but that is not what i get, i get these numbers:

102
2000
36
42
520
5400
....

it does order in some kind of a way, but that is not what i want. Maybe there is another way to sort the data how i want it.

Adding this as an answer (transferred from my comment) since it seems the question is now resolved. Can you please mark this question as resolved?

Your money field is stored as strings. And so its being sorted appropriately as a string. If you want it sorted numerically, you need to convert to a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM