无法将数据插入或检索到MongoDB

时间:2019-05-07 20:55:33

标签: mongodb pymongo

我尝试从MongoDB中插入和提取一些数据。 按照mongodb.com上的指示正确设置了连接

try:
    client = MongoClient(
        'mongodb+srv://user:pw!@cluster0-nghj0.gcp.mongodb.net/test?retryWrites=true',
        ssl=True)
    print("connected")
except:
    print('failed')

我手动创建一个数据库:messager.messager并在其中放入一些json文件

当我尝试使用collection.find()collection.insert_one(...)

db = client.messager
collection = db.messager

for i in collection.find():
    print(i)

它返回超时错误:

File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/cursor.py", line 1225, in next
    if len(self.__data) or self._refresh():
  File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/cursor.py", line 1117, in _refresh
    self.__session = self.__collection.database.client._ensure_session()
  File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1598, in _ensure_session
    return self.__start_session(True, causal_consistency=False)
  File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1551, in __start_session
    server_session = self._get_server_session()
  File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1584, in _get_server_session
    return self._topology.get_server_session()
  File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/topology.py", line 434, in get_server_session
    None)
  File "/Users/anhnguyen/Documents/GitHub/GoogleCloud_Flask/comming soon/env/lib/python3.7/site-packages/pymongo/topology.py", line 200, in _select_servers_loop
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed

哪里出错了? 这是我的Mongodb.com设置: enter image description here

1 个答案:

答案 0 :(得分:0)

pymongo documentation for errors中,您遇到以下问题。

异常pymongo.errors.ServerSelectionTimeoutError(message ='',errors = None)

没有MongoDB服务器可用于操作时抛出

如果没有适合该操作的服务器,PyMongo会尝试使用serverSelectionTimeoutMS(默认为30秒)来查找一个服务器,然后抛出此异常。例如,当PyMongo无法连接到任何服务器时,或者如果您尝试插入没有主副本且在超时窗口内没有选择主副本的副本集时,或者尝试使用a查询时,抛出该异常。读取副本集无法满足的首选项。

您必须检查您的网络是否与MongoDB服务器所在的网络具有良好的连接性。 可能会出现副本集主节点无响应的情况。在这种情况下,您需要重新启动集群(如果您具有访问权限)。

此外,按如下所示创建连接:

mongo_conn = MongoClient('mongodb+srv://cluster0-nghj0.gcp.mongodb.net/test?retryWrites=true', username=your_username, password=pwd, authSource='admin', authMechanism='SCRAM-SHA-1')

以上是可遵循的最佳实践。 mongodb+srv网址不需要提及ssl=True