Frage

How do i iterate over all the documents in a collection sorted by my unique id (uid) field to retrieve the `"eng" field?

My document structure looks like this:

{ "_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 }

Why doesn't the sort work:

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"]

I get this 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

When i did this, it worked:

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

Lösung

Your sort() syntax is off, it should be:

for i in v7.find({"eng":{"$exist":True}}).sort("uid", pymongo.DESCENDING):
    print i["eng"]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top