Pymongo-未被授权在数据库上执行命令

3

我在 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 Domscheit
也许数据库名称db不是很聪明,因为在MongoDB中,db是一个预定义对象。通常情况下,您可以跳过authMechanism=...。如果您从mongo shell运行相同的命令,它能工作吗? - Wernfried Domscheit
密码中是否有需要转义的字符?请参阅标准连接字符串格式 - Wernfried Domscheit
@WernfriedDomscheit 我不是这个服务器的管理员,我只有一个用户的访问权限。我的意思是,当我在服务器上找到关于这个用户的信息时,这些角色和数据库都在同一个括号内,所以我认为它们是相互关联的。{"role" : "dbOwner", "db" : "db"} 我猜想这些角色不是由我创建的,而是内置的角色。我的密码中没有需要转义的字符。 - jedrek
1
请注意,角色 dbOwner 包括 readWrite,即 readWrite 是多余的。 - Wernfried Domscheit
显示剩余9条评论
1个回答

0

我找到了答案。我不太清楚有什么区别,但在我的情况下,我必须创建一个函数来获取光标。

def get_database():

    from pymongo import MongoClient
    import pymongo

    # Provide the mongodb url to connect python to mongodb using pymongo
    CONNECTION_STRING = "mongodb://user:password@cluster:111111/db?ssl=true&connectTimeoutMS=10000&authSource=db&authMechanism=SCRAM-SHA-1"

    # Create a connection using MongoClient. 
    from pymongo import MongoClient
    client = MongoClient(CONNECTION_STRING)

    # Create the database
    return client['db']

然后使用此函数创建光标

dbname = get_database()

collection_name = dbname["collection_name"]

item_details = collection_name.find(condition)
for item in item_details:
    print(item)

使用这种方法一切都正常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接