我试图在查询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
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。
发布于 2011-11-13 10:22:39
.sort()
,在pymongo,采取key
和direction
作为参数。
所以如果你想排序,比方说,id
那么你应该.sort("_id", 1)
对于多个字段:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
发布于 2014-09-11 15:16:22
你可以试试这个:
db.Account.find().sort("UserName")
db.Account.find().sort("UserName",pymongo.ASCENDING)
db.Account.find().sort("UserName",pymongo.DESCENDING)
发布于 2015-03-12 19:04:48
这也是可行的:
db.Account.find().sort('UserName', -1)
db.Account.find().sort('UserName', 1)
我在我的代码中使用了这个,如果我在这里做错了什么,请发表意见,谢谢。
https://stackoverflow.com/questions/8109122
复制相似问题