[英]Pymongo - not authorized on db to execute command
我在 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 中檢查了一些關於這個問題的線程,但是,它們都不適合我的情況。 我只想查詢創建了我正在使用的用戶的數據庫
我找到了答案。 我真的不知道有什么區別,但就我而言,我必須創建一個函數來獲取光標。
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)
使用這種方法一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.