我在查询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”,但这也不起作用。任何其他人都可以使用它,或者这是一个错误。
.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])
对多个字段进行排序。