1、数据库
{'cishu': 372, 'title': '镇中心小学厕所问题'}
{'cishu': 388, 'title': '私搭乱建'}
{'cishu': 222, 'title': '新生儿落户收费么?'}
{'cishu': 341, 'title': '44路车不按时间发车越来越严重'}
2、我想以cishu为参考做个排序
for i in info.find({},{'title':1,'_id':0}).sort({"cishu":-1}):
print(i)
我写了这个进行排序,总是报错,刚初学,不知道怎么做这个排序。。。
报错内容
TypeError: if no direction is specified, key_or_list must be an instance of list
3、弄不明白之后,然后我尝用管道进行排序,倒是出来了结果,只有次数,不会把title弄出来。。。
def cishu():
pipeline = [
{'$group': {'_id':'$cishu'}},
{'$sort':{'_id':-1}},
{'$limit':100}
]
for i in item_info.aggregate(pipeline):
data = {
'name': i['_id'],
}
print(i)
出来的结果是
{'_id': 388}
{'_id': 372}
{'_id': 341}
{'_id': 222}
我想要的结果是
{'cishu': 388, 'title': '私搭乱建'}
{'cishu': 372, 'title': '镇中心小学厕所问题'}
{'cishu': 341, 'title': '44路车不按时间发车越来越严重'}
{'cishu': 222, 'title': '新生儿落户收费么?'}
我怎么让他全面的出来结果。。。小白苦恼,请大侠帮忙看看
PHP中文网2017-04-18 09:57:35
Writing like this in sort [("cishu",pymongo.DESCENDING)], if multi-value sorting is [("key1",pymongo.DESCENDING),("key2":pymongo.DESCENDING)]. See the code for details
from pymongo import MongoClient
import pymongo
client = MongoClient()
#创建连接
conn = MongoClient('127.0.0.1', 27017)
#连接数据库
db = conn.qwer
datas = db.test.find({}, {"cishu":1,"title":1,"_id":0}).sort([("cishu",pymongo.DESCENDING)])
for data in datas:
print(data)
大家讲道理2017-04-18 09:57:35
Code:
info = [
{'cishu': 372, 'title': '镇中心小学厕所问题'},
{'cishu': 388, 'title': '私搭乱建'},
{'cishu': 222, 'title': '新生儿落户收费么?'},
{'cishu': 341, 'title': '44路车不按时间发车越来越严重'}
]
for item in sorted(info, key=lambda dic: dic['cishu'], reverse=True):
print(item)
Result:
{'cishu': 388, 'title': '私搭乱建'}
{'cishu': 372, 'title': '镇中心小学厕所问题'}
{'cishu': 341, 'title': '44路车不按时间发车越来越严重'}
{'cishu': 222, 'title': '新生儿落户收费么?'}
Questions I answered: Python-QA
PHPz2017-04-18 09:57:35
Why not sort when querying the database?
select * from xxx order by cishu desc