0

I'm having trouble sorting data by price. I want to show off the price based on the value of the price I've tried, but the results are not as I expected.

code testing:

from pymongo import MongoClient
client = MongoClient().ecome
col = client['post_product']

data = []
GetData = col.find({'Category':'Handphone'}).sort([('Price', pymongo.ASCENDING)]).limit(10)
for x in GetData:
    listed = dict(
        title=x['Title'],
        price=x['Price']
    )
    data.append(listed)

print data

and the result:

[{
    'price': '10',
    'title': 'tresemse'
}, {
    'price': '200',
    'title': 'muaral winner'
}, {
    'price': '30',
    'title': 'troboca'
}, {
    'price': '400',
    'title': 'brek yule'
}, {
    'price': '50',
    'title': 'moun yus'
}]

the results I expect are:

[{
    'price': '10',
    'title': 'tresemse'
}, {
    'price': '30',
    'title': 'troboca'
}, {
    'price': '50',
    'title': 'moun yus'
}, {
    'price': '200',
    'title': 'muaral winner'
}, {
    'price': '400',
    'title': 'brek yule'
}]

please help !

Siska Brilian
  • 61
  • 1
  • 4

2 Answers2

1

This is how strings are sorted. You should change Price field to number if you want it to be sorted as a number and not as a string. There's no way Mongo can assume it's a number when it's not.

tbking
  • 8,796
  • 2
  • 20
  • 33
0

just put the following at the end of your code;

data.sort(key = lambda item: float(item["price"]))
Treehee
  • 117
  • 1
  • 2
  • 11