迭代MongoDB集合时出现UnicodeDecodeError

时间:2012-10-04 12:49:29

标签: python mongodb python-2.7 pymongo

我正在尝试使用Python 2.7和pymongo-2.3使用以下内容查询MongoDB数据库:

from pymongo import Connection

connection = Connection()
db = connection['db-name']
collections = db.subName
entries = collections['collection-name']
print entries 
# > Collection(Database(Connection('localhost', 27017), u'db-name'), u'subName.collection-name')

for entry in entries.find():
    pass

即使我对entry对象没有做任何事情,迭代器也会失败:

Traceback (most recent call last):
File "/Users/../mongo.py", line 27, in <module>
  for entry in entries.find():
File "/Library/Python/2.7/site-packages/pymongo-2.3-py2.7-macosx-10.8-intel.egg/pymongo/cursor.py", line 778, in next
File "/Library/Python/2.7/site-packages/pymongo-2.3-py2.7-macosx-10.8-intel.egg/pymongo/cursor.py", line 742, in _refresh
File "/Library/Python/2.7/site-packages/pymongo-2.3-py2.7-macosx-10.8-intel.egg/pymongo/cursor.py", line 686, in __send_message
File "/Library/Python/2.7/site-packages/pymongo-2.3-py2.7-macosx-10.8-intel.egg/pymongo/helpers.py", line 111, in _unpack_response
UnicodeDecodeError: 'utf8' codec can't decode byte 0xfc in position 744: invalid start byte

我不是我想要查询的数据库的创建者。 有人知道我做错了什么以及如何解决它?感谢。


更新:我设法使用pymongo/helpers.py跳过来自try-except的违规行,但我更倾向于不涉及数据丢失的解决方案。

try:
    result["data"] = bson.decode_all(response[20:], as_class, tz_aware, uuid_subtype)
except:
    result["data"] = []

1 个答案:

答案 0 :(得分:2)

您可以使用mongo shell尝试相同的操作吗?我想弄清楚它是特定于Python的还是数据库中的损坏:

$ mongo db-name  
> var collection = db.getCollection('subName.collection-name')  
> collection.find().forEach(function(doc) { printjson(doc); })
相关问题