Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k 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.

2 Answers

0 votes
by (106k 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)])

0 votes
by (107k points)

You can also try the following code:

db.Account.find().sort("UserName")  

db.Account.find().sort("UserName",pymongo.ASCENDING)   

db.Account.find().sort("UserName",pymongo.DESCENDING)  

Related questions

0 votes
2 answers
0 votes
1 answer
asked Oct 18, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
0 votes
2 answers
asked Sep 4, 2019 in SQL by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...