如何用pymongo对mongodb进行排序
我在查询我的mongoDB时想用排序功能,但它失败了。相同的查询在MongoDB控制台里可以正常工作,但在这里却不行。代码如下:
import pymongo
from pymongo import Connection
connection = Connection()
db = connection.myDB
print db.posts.count()
for post in db.posts.find({}, {'entities.user_mentions.screen_name':1}).sort({u'entities.user_mentions.screen_name':1}):
print post
我遇到的错误是:
Traceback (most recent call last):
File "find_ow.py", line 7, in <module>
for post in db.posts.find({}, {'entities.user_mentions.screen_name':1}).sort({'entities.user_mentions.screen_name':1},1):
File "/Library/Python/2.6/site-packages/pymongo-2.0.1-py2.6-macosx-10.6-universal.egg/pymongo/cursor.py", line 430, in sort
File "/Library/Python/2.6/site-packages/pymongo-2.0.1-py2.6-macosx-10.6-universal.egg/pymongo/helpers.py", line 67, in _index_document
TypeError: first item in each key pair must be a string
我在其他地方找到一个链接,说如果使用pymongo的话,需要在键前面加个'u',但这样也没用。有没有其他人能让这个工作,还是说这是个bug?
9 个回答
25
这个方法也可以用:
db.Account.find().sort('UserName', -1)
db.Account.find().sort('UserName', 1)
我在我的代码中使用了这个,如果我有什么做错的地方,请留言告诉我,谢谢。
44
你可以试试这个:
db.Account.find().sort("UserName")
db.Account.find().sort("UserName",pymongo.ASCENDING)
db.Account.find().sort("UserName",pymongo.DESCENDING)
386
.sort()
是 pymongo 中用来排序的一个方法,它需要两个参数:key
和 direction
。
比如,如果你想按照 id
来排序,你应该使用 .sort("_id", 1)
。
如果要按多个字段排序:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])