我在 MongoDB 中有这个用户
{
"_id" : "xxx",
"userId" : UUID("xxx"),
"user" : "user",
"db" : "db",
"roles" : [
{
"role" : "dbOwner",
"db" : "db"
},
{
"role" : "readWrite",
"db" : "db"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
这是我的连接字符串:
Connection_string= 'mongodb://user:password@cluster:111111/db?ssl=false&connectTimeoutMS=10000&authSource=db&authMechanism=SCRAM-SHA-1'
在Studio 3T中使用这个连接字符串查询数据没有问题,但是在pymongo中使用它时出现了错误。这是我的代码:
from pymongo import MongoClient
client = MongoClient(Connection_string)
db=client.db
collection = db.collection_name
coursor= collection.find({})
for r in coursor:
print (r)
这是一个错误信息
OperationFailure: not authorized on db to execute command { find: "collection_name", filter: {}, lsid: { id: UUID("xx") }, $clusterTime: { clusterTime: Timestamp(1654866078, 1), signature: { hash: BinData(0, xx), keyId: xx} }, $db: "db" }, full error: {'operationTime': Timestamp(1654866078, 1), 'ok': 0.0, 'errmsg': 'not authorized on db to execute command { find: "collection_name", filter: {}, lsid: { id: UUID("xx") }, $clusterTime: { clusterTime: Timestamp(1654866078, 1), signature: { hash: BinData(0, xx), keyId: xx} }, $db: "db" }', 'code': 13, 'codeName': 'Unauthorized', '$clusterTime': {'clusterTime': Timestamp(1654866078, 1), 'signature': {'hash': b'xxxx', 'keyId': xx}}}
我在StackOverflow查看了一些相关的帖子,但是它们都不适用于我的情况。我想只查询创建了当前用户的数据库。
db
中创建,但您输入了authSource=OSCAR
。请访问 https://dev59.com/YlMHtIcB2Jgan1zn8Iss#63755470。 - Wernfried Domscheitdb
不是很聪明,因为在MongoDB中,db
是一个预定义对象。通常情况下,您可以跳过authMechanism=...
。如果您从mongo shell运行相同的命令,它能工作吗? - Wernfried Domscheit{"role" : "dbOwner", "db" : "db"}
我猜想这些角色不是由我创建的,而是内置的角色。我的密码中没有需要转义的字符。 - jedrekdbOwner
包括readWrite
,即readWrite
是多余的。 - Wernfried Domscheit