카테고리 없음

[MongoDB] 몽고디비 python 에 연결하기

곽진돔 2023. 8. 7. 16:18

pymongo 모듈을 사용하여 몽고디비에 연결하려고 했는데 인증에러로 연결이 안되었다.

쉘에서는 잘 접속 되었건만,,로컬에서 하니까 안된다 ㅠ 

pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

계속 연결이 안되서 고민이였는데 아래 사이트를 참고하여 해결하였다.

https://stackoverflow.com/questions/72048051/pymongo-auth-failure-ok-0-0-errmsg-authentication-failed-code-18

 

PyMongo Auth Failure: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'

Curious thing, I am running SLS Python Lambdas in a Docker container with the MongoDB instance in a separate container. I am able to authenticate from an exposed port on my host to connect to the

stackoverflow.com

인증 데이터베이스를 admin 으로 설정해줘야되나보다.

클라이언트 정보에 ?authSource=admin&retryWrites=true&w=majority 를 넣어준다.

?authSource=admin&retryWrites=true&w=majority

아래 코드로 DB 연결 테스트를 하면 된다. 몽고디비의 기본 포트번호는 27017이다.

import pandas as pd
import pymysql
from pymongo import MongoClient
from sqlalchemy import create_engine

MONGO_HOST = "HOST"
MONGO_PORT = "27017"
MONGO_DB = "DBNAME"
MONGO_USER = "USERNAME"
MONGO_PASS = "PASSWORD"
COLLECTIONNAME = "COLLECTIONNAME"
try:
    client = MongoClient(
        f"mongodb://{MONGO_USER}:{MONGO_PASS}@{MONGO_HOST}:{MONGO_PORT}/{MONGO_DB}?authSource=admin&retryWrites=true&w=majority")
    db = client.DBNAME
    collection = db.COLLECTIONNAME
    
    doc = collection.find({})
    for item in doc:
        print(item) 
except Exception as e:
    print('실패', e)