0 votes
1 view
in SQL by (28.2k points)

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

The error I get is as follows:

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

I found a link elsewhere that says I need to place a 'u' in front of the key if using pymongo, but that didn't work either. Anyone else gets this to work or is this a bug.

1 Answer

0 votes
by (68.3k points)

If you want to sort MongoDB with pymongo you can use the below-mentioned way:-

The .sort(), in pymongo, takes key and direction as parameters.

So if you want to sort by, let's say, id then you should .sort("_id", 1)

For multiple fields:

.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])

...