如何使用pymongo迭代按整数字段排序的集合中的所有文档?

时间:2013-01-31 04:15:20

标签: mongodb pymongo data-retrieval database

如何迭代按我的唯一ID(uid)字段排序的集合中的所有文档以检索“eng”字段?

我的文档结构如下:

{ "_id" : ObjectId("50fd55c1161747668078fed6"), "dan" : "Hr. Hänsch repræsenterede Dem dér .", "deu" : "Der Kollege Hänsch hat Sie dort vertreten .", "eng" : "Mr Hänsch represented you on this occasion .", "fin" : "Kollega Hänsch edusti teitä siellä .", "ita" : "Il collega Hänsch è intervenuto in sua vece .", "md5" : "336b9cd1dc01ae0ff3344072d8db0295", "uid" : 2100986 }

为什么排序不起作用:

connection = MongoClient()
db = connection["europarl"] # The database.
v7 = db["v7"] # The collection

for i in v7.find({"eng":{"$exist":True}}).sort({"uid":-1}):
    print i["eng"]

我得到了这个TypeError:

Traceback (most recent call last):
  File "mongo_lemma.py", line 67, in <module>
    for i in v7.find({"eng":{"$exists":True}}).sort({"uid":"1"}):
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/pymongo/cursor.py", line 513, in sort
    keys = helpers._index_list(key_or_list, direction)
  File "/usr/local/lib/python2.7/dist-packages/pymongo-2.4.1-py2.7-linux-x86_64.egg/pymongo/helpers.py", line 47, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list

当我这样做时,它起作用了:

for i in v7.find({"eng":{"$exist":True}}):
    print i["eng"]

1 个答案:

答案 0 :(得分:1)

您的sort()语法已关闭,应为:

for i in v7.find({"eng":{"$exist":True}}).sort("uid", pymongo.DESCENDING):
    print i["eng"]