我试图在查询我的mongoDB时使用排序功能,但它失败了。同样的查询在MongoDB控制台中有效,但在这里无效。代码如下:

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

我得到的错误如下:

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

我在其他地方找到了一个链接,说如果使用pymongo,我需要在键的前面放置一个“u”,但这也不起作用。还有谁能搞定这个吗,还是这是个bug。


当前回答

描述& asc:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]

doc = col.find().sort("name", -1) #

for x in doc:
  print(x)

###################

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]

doc = col.find().sort("name", 1) #

for x in doc:
  print(x)

其他回答

描述& asc:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]

doc = col.find().sort("name", -1) #

for x in doc:
  print(x)

###################

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]

doc = col.find().sort("name", 1) #

for x in doc:
  print(x)

.sort()在pymongo中以键和方向作为参数。

如果你想通过id来排序那么你可以输入。sort("_id", 1)

对于多个字段:

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

你可以试试这个:

db.Account.find().sort("UserName")  
db.Account.find().sort("UserName",pymongo.ASCENDING)   
db.Account.find().sort("UserName",pymongo.DESCENDING)  
.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

Python使用键,方向。你可以用上面的方法。

在你的例子中,你可以这样做

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

这也是可行的:

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

我在我的代码中使用这个,如果我在这里做错了,请评论,谢谢。