如何使用 pymongo 对 mongodb 进行排序 [英] How to sort mongodb with pymongo
问题描述
我在查询 mongoDB 时尝试使用排序功能,但它失败了.相同的查询在 MongoDB 控制台中有效,但在此处无效.代码如下:
I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows:
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",但这也不起作用.其他任何人都可以使用它,或者这是一个错误.
I found a link elsewhere that says I need to place a 'u' infront of the key if using pymongo, but that didn't work either. Anyone else get this to work or is this a bug.
推荐答案
.sort()
,在 pymongo 中,采用 key
和 direction
作为参数.
.sort()
, in pymongo, takes key
and direction
as parameters.
所以如果你想排序,比方说,id
那么你应该 .sort("_id", 1)
So if you want to sort by, let's say, id
then you should .sort("_id", 1)
对于多个字段:
.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])
这篇关于如何使用 pymongo 对 mongodb 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!