How to sort mongodb with pymongo

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' 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(), 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)])

Python MongoDB Sort, .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� Sort the Result. Use the sort() method to sort the result in ascending or descending order. The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).


You can try this:

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

How to sort mongodb with pymongo, When a call is made to query documents, MongoDB returns a pymongo.cursor. Cursor object containing data about the query's results. This cursor� The most common reason for a failure when sorting MongoDB documents with PYMongo sort method is usually tied to not all of the documents having an integer for the data type. Also remember, the number representing the second item of the tuple object passed to sort () is the sort order, with 1 for ASCENDING and -1 for DESCENDING order.


This also works:

db.Account.find().sort('UserName', -1)
db.Account.find().sort('UserName', 1)

I'm using this in my code, please comment if i'm doing something wrong here, thanks.

How To Sort MongoDB Documents In A Collection Using Python , cursor. sort (sort)�. mongo Shell Method. This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver)� 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)


Why python uses list of tuples instead dict?

In python you cannot guarantee that dictionary will be interpreted in the order you declared.

So, in mongo shell you could do .sort({'field1':1,'field2':1}) and the interpreter should sort field1 at first level and field 2 at second level.

If this sintax was used in python, there is a chance to sort field2 at first level. With tuple there is no risk.

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

cursor.sort(), In the mongo shell, use cursor.sort() instead. The $orderby operator sorts the results of a query in ascending or descending order. The mongo shell provides the� I tried aggregate, seems pymongo doesn't support aggregate, I tried db.command, still it failed, I will experiment, the second method seems to be straight forward, I am concerned about complexity and round trip time, since this is run across few thousand to few hundred thousand dosc(at present 10k).


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

Python uses key,direction. You can use the above way.

So in your case you can do this

for post in db.posts.find().sort('entities.user_mentions.screen_name',pymongo.ASCENDING):
        print post

$orderby — MongoDB Manual, See Metadata Sort for an example. If sorting on multiple fields, sort order is evaluated from left to right. For example, in the form above, documents are first sorted� Sort and Index Use¶ The sort can sometimes be satisfied by scanning an index in order. If the query plan uses an index to provide the requested sort order, MongoDB does not perform an in-memory sorting of the result set. For more information, see Use Indexes to Sort Query Results.


$sort (aggregation) — MongoDB Manual, for doc in collection.find().sort([ ('field1', pymongo.ASCENDING), ('field2', pymongo.DESCENDING)]): print(doc). Beginning with MongoDB version 2.6, text � Ascending/Descending Sort ¶. For the field or fields to sort by, set the sort order to 1 or -1 to specify an ascending or descending sort respectively, as in the following example: This operation sorts the documents in the users collection, in descending order according by the age field and then in ascending order according to the value in the posts field.


cursor – Tools for iterating over MongoDB query results — PyMongo , Python program that uses sort from pymongo import MongoClient client = MongoClient("mongodb://127.0.0.1:27017") db = client.search_engines # Reset. MongoDB noob here Ok, I have a collection of students, each with a record that looks like the following. I want to sort the 'type' : 'homework' scores in descending order.


sort - pymongo - Python documentation, Sorting and limiting are very simple. We often combine them to make our output readable. Not only can you input them in your aggregating framework, but you can also use it as a Python method. from pymongo import DESCENDING sort_key = "imdb.rating" movies = client.sample_mflix.movies.find({}) \.sort(sort_key, DESCENDING).limit(100) list(movies)