常见问题#
另请参阅 TLS错误故障排除 一节。
服务器报告有线版本X,PyMongo需要Y#
当用户尝试连接到低于3.4版的服务器时,PyMongo将抛出以下错误:
>>> client.admin.command('ping')
...
pymongo.errors.ConfigurationError: Server at localhost:27017 reports wire version 5, but this version of PyMongo requires at least 6 (MongoDB 3.6).
这是因为驱动程序对于运行它的服务器来说太新了。要解决此问题,要么将您的数据库升级到版本>=3.6,要么降级到支持MongoDB>=2.6的PyMongo 3.x。
“Cursor”对象没有属性“_CURSOR__KILL”#
在版本低于3.9的PyMongo上,当向游标的构造函数提供无效参数时,将引发TypeError,并将AttributeError打印到 stderr
。AttributeError无关紧要,请查看TypeError以获取调试信息::
>>> coll.find(wrong=1)
Exception ignored in: <function Cursor.__del__ at 0x1048129d8>
...
AttributeError: 'Cursor' object has no attribute '_Cursor__killed'
...
TypeError: __init__() got an unexpected keyword argument 'wrong'
要解决此问题,请确保您提供的关键字参数正确。此外,您还可以升级到PyMongo>=3.9,这将消除虚假错误。
MongoClient无法配置错误#
这是由于使用不正确的关键字参数名称而导致的常见问题。
>>> client = MongoClient(wrong=1)
...
pymongo.errors.ConfigurationError: Unknown option wrong
要解决此问题,请检查您的拼写,并确保您指定的关键字参数存在。
已弃用警告:已弃用计数#
PyMongo不再支持 pymongo.cursor.count()
。相反,您可以使用 pymongo.collection.count_documents()
**
>>> client = MongoClient()
>>> d = datetime.datetime(2009, 11, 12, 12)
>>> list(client.db.coll.find({"date": {"$lt": d}}, limit=2))
[{'_id': ObjectId('6247b058cebb8b179b7039f8'), 'date': datetime.datetime(1, 1, 1, 0, 0)}, {'_id': ObjectId('6247b059cebb8b179b7039f9'), 'date': datetime.datetime(1, 1, 1, 0, 0)}]
>>> client.db.coll.count_documents({"date": {"$lt": d}}, limit=2)
2
请注意,这不同于 Cursor.count_documents
(它不存在),则这是Collection类的方法,因此必须在集合对象上调用它,否则将收到以下错误:
>>> Cursor(MongoClient().db.coll).count()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Cursor' object has no attribute 'count'
>>>
通过隧道从PyMongo访问MongoDB时超时#
尝试通过SSH隧道连接到副本集MongoDB实例时,您将收到以下错误:
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 1560, in count
return self._count(cmd, collation, session)
File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 1504, in _count
with self._socket_for_reads() as (connection, slave_ok):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Library/Python/2.7/site-packages/pymongo/mongo_client.py", line 982, in _socket_for_reads
server = topology.select_server(read_preference)
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 224, in select_server
address))
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 183, in select_servers
selector, server_timeout, address)
File "/Library/Python/2.7/site-packages/pymongo/topology.py", line 199, in _select_servers_loop
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: timed out
这是因为,PyMongo使用来自isMaster命令的响应发现副本集成员,然后该命令包含其他成员的地址和端口。但是,这些地址和端口将无法通过SSH隧道访问。因此,此行为不受支持。但是,您可以使用带有SSH隧道的directConnection=True选项直接连接到单个MongoDB节点。