You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pymongo连接MongoDB时出现IndexError: pop from an empty deque错误

MongoDB连接报错解决方法

核心错误为MongoDB Atlas身份认证失败(错误代码8000),由密码特殊符号的URL编码错误导致,解决步骤如下:

  • 特殊字符编码要求:MongoDB连接字符串中的特殊符号(包括!、@、#、$等保留字符)必须进行百分号编码,你密码开头的感叹号!对应的编码为%21,不可直接写入连接字符串,你当前代码中%33%password属于错误的编码格式,是认证失败的直接诱因。
  • 推荐自动编码方案:使用Python内置的urllib.parse.quote_plus方法自动处理密码,避免手动编码出错,修改后的完整代码如下:
import pymongo
from pymongo import MongoClient
import dns.resolver
from urllib.parse import quote_plus

dns.resolver.default_resolver=dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers=['8.8.8.8']

# 填写原始用户名和未编码的真实密码
username = "gabriel"
origin_password = "!你的真实密码"
encoded_password = quote_plus(origin_password)

# 拼接合法连接字符串
cluster = pymongo.MongoClient(f"mongodb+srv://{username}:{encoded_password}@cluster1.ez4er.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")

db = cluster["gabdatabase"]
collection = db["learningmongo"]

print(cluster.list_database_names())
  • 异常排查项:若修改后仍报错,依次确认:
    • MongoDB Atlas后台配置的用户名、密码完全匹配,无拼写错误
    • 当前设备的公网IP已添加到Atlas的访问白名单中
    • 该数据库账号已配置对应数据库的访问权限

内容的提问来源于stack exchange,提问作者python_man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:09:03