How to sort mongodb with pymongo
NickName:WildBill Ask DateTime:2011-11-13T10:13:58

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.

Copyright Notice:Content Author:「WildBill」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/8109122/how-to-sort-mongodb-with-pymongo

Answers
romulomadu 2018-02-06T00:35:30

Why python uses list of tuples instead dict?\nIn python, you cannot guarantee that the dictionary will be interpreted in the order you declared.\nSo, in mongo shell you could do .sort({'field1':1,'field2':1}) and the interpreter would sort field1 at first level and field 2 at second level.\nIf this syntax was used in python, there is a chance of sorting by field2 at first level. With tuple, there is no such risk.\n.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])\n",


An Se 2021-02-25T10:57:30

Sort by _id descending:\ncollection.find(filter={"keyword": keyword}, sort=[( "_id", -1 )])\n\nSort by _id ascending:\ncollection.find(filter={"keyword": keyword}, sort=[( "_id", 1 )])\n",


Ayse 2021-08-10T11:26:58

DESC & ASC :\nimport pymongo\n\nclient = pymongo.MongoClient("mongodb://localhost:27017/")\ndb = client["mydatabase"]\ncol = db["customers"]\n\ndoc = col.find().sort("name", -1) #\n\nfor x in doc:\n print(x)\n\n###################\nimport pymongo\n\nclient = pymongo.MongoClient("mongodb://localhost:27017/")\ndb = client["mydatabase"]\ncol = db["customers"]\n\ndoc = col.find().sort("name", 1) #\n\nfor x in doc:\n print(x)\n",


Anuj Gupta 2019-11-06T11:25:31

TLDR: Aggregation pipeline is faster as compared to conventional .find().sort().\n\nNow moving to the real explanation. There are two ways to perform sorting operations in MongoDB:\n\n\nUsing .find() and .sort().\nOr using the aggregation pipeline.\n\n\nAs suggested by many .find().sort() is the simplest way to perform the sorting.\n\n.sort([(\"field1\",pymongo.ASCENDING), (\"field2\",pymongo.DESCENDING)])\n\n\nHowever, this is a slow process compared to the aggregation pipeline. \n\nComing to the aggregation pipeline method. The steps to implement simple aggregation pipeline intended for sorting are:\n\n\n$match (optional step)\n$sort\n\n\nNOTE: In my experience, the aggregation pipeline works a bit faster than the .find().sort() method.\n\nHere's an example of the aggregation pipeline.\n\ndb.collection_name.aggregate([{\n \"$match\": {\n # your query - optional step\n }\n},\n{\n \"$sort\": {\n \"field_1\": pymongo.ASCENDING,\n \"field_2\": pymongo.DESCENDING,\n ....\n }\n}])\n\n\nTry this method yourself, compare the speed and let me know about this in the comments.\n\nEdit: Do not forget to use allowDiskUse=True while sorting on multiple fields otherwise it will throw an error.",


Ash Upadhyay 2017-03-27T06:01:11

.sort([(\"field1\",pymongo.ASCENDING), (\"field2\",pymongo.DESCENDING)])\n\n\nPython uses key,direction. You can use the above way.\n\nSo in your case you can do this\n\nfor post in db.posts.find().sort('entities.user_mentions.screen_name',pymongo.ASCENDING):\n print post\n",


Ben 2011-11-13T02:22:38

.sort(), in pymongo, takes key and direction as parameters.\nSo if you want to sort by, let's say, id then you should .sort("_id", 1)\nFor multiple fields:\n.sort([("field1", pymongo.ASCENDING), ("field2", pymongo.DESCENDING)])\n",


new_light 2014-09-11T07:16:21

You can try this:\n\ndb.Account.find().sort(\"UserName\") \ndb.Account.find().sort(\"UserName\",pymongo.ASCENDING) \ndb.Account.find().sort(\"UserName\",pymongo.DESCENDING) \n",


Snehal Parmar 2015-03-12T11:04:47

This also works:\n\ndb.Account.find().sort('UserName', -1)\ndb.Account.find().sort('UserName', 1)\n\n\nI'm using this in my code, please comment if i'm doing something wrong here, thanks.",


More about “How to sort mongodb with pymongo” related questions

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

Show Detail

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

Show Detail

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

Show Detail

sort by string length in Mongodb/pymongo

I was wondering if anyone knows how to sort a mongodb find() result by string length. I have tried something like db.foo.find().sort({item.lenght:-1}) but obviously doesn't work. Can somebody help...

Show Detail

Pymongo auto sort the input dictionary

I am using Pymongo to access Mongo db. I want to search for all people nearby a specified location with name contains a string. For example, I want to search all people nearby [105.0133, 21.3434] and

Show Detail

PyMongo sort with metadata

I wondering how to convert the follow mongodb query to pymongo syntax db.articles.find( { $text: { $search: "cake" } }, { score: { $meta: "textScore" } } ).sort( { score: { $meta: "textScore...

Show Detail

find documents that mongodb moves with pymongo

I am trying to count in my mongodb profiler data all the documents, that have been moved when they were updated. In the mongo shell I do this via: db.system.profile.find({op:"update", moved:true}).

Show Detail

How do I sort array of dictionaries in Pymongo?

I have this example MongoDB entry in a users DB: { _id: xxx, name: &quot;name&quot;, files:[{ fileName: &quot;test&quot;, size: 50 }, { ...

Show Detail

speed up writing to mongoDB with pymongo

I am working on an API for data from a weather model - not anything that will run in production. I use MongoDB to hold the data. The data are gridded with dimension [Time: X, Latitude: 1100, Longit...

Show Detail

MongoDB sort overflow with PyMongo

I have collection "doc" containing a field called "topic". It is initialized to -1 and when I get the topic, I update the field with the corresponding topic e.g. sports. When I do a query in PyMong...

Show Detail