如何使用pymongo对mongodb进行排序 [英] How to sort mongodb with pymongo
本文介绍了如何使用pymongo对mongodb进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在查询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()
以key
和direction
作为参数.
因此,如果要按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屋!
查看全文