Mongodb pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] 连接被拒绝,超时:30s,

问题描述

我正在尝试在本地连接到我的数据库。我已经在 MongoDB Compass 上建立了到数据库的连接,但是当我运行我的简单代码时,我收到了这个错误

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] 连接被拒绝,超时:30 秒,拓扑描述: ]> root@LAPTOP-8OKVP35I:/portfolio/myProjects/webDevelopment/shopify_db#

这是我正在运行的代码

import pymongo
from pymongo import MongoClient

client = pymongo.MongoClient()
db = client["Shopper_Info"]
my_collection = db["Names"]
shopper_data = {'name': 'Yoni','email': 'test@gmail.com'}

my_collection.insert_one(shopper_data)

results= collection.find({"name": 'Yoni'})

for result in results:
print(result)

解决方法

这个问题也发生在我的堆栈中,我在一个 env 文件中有我的连接字符串来连接到 mongo atlas。

MONGO_URI=mongodb://<username>:<password>@cluster-details

但正确的做法是

MONGO_URI="mongodb://<username>:<password>@cluster-details"