kazuuu.net

テクノロジー・データ分析・実践ログ・その他

Pythonでpymongoを用いてMongoDBAtlasに接続する

カテゴリ: Python【初歩から現場実務的なもの】

Pythonでpymongoを用いてMongoDBAtlasに接続してみます。

今回、pymongoモジュールを用います。このライブラリ・モジュールはPythonの標準ライブラリではありませんので、事前にインストールする必要があります。

なお、MongoDBAtlasに接続する場合は、mongo+srvプロトコルを使用する必要があるため、

pip install pymongo[srv]

上記のコマンドでpip経由でpymongo-srvをインストールする。これがないと「dnspython module must be installed to use mongodb+srv:// URI」というエラーが発生し、接続できない。

■Python

今回のPythonのバージョンは、「3.8.5」を使用しています。(Windows10)(pythonランチャーでの確認)

■pymongoを用いてMongoDBAtlasに接続する

では、早速pymongoを用いてMongoDBAtlasに接続するスクリプトを書いていきます。

■コード

import pymongo  

client = pymongo.MongoClient("接続するためのコード")

for name in client.list_database_names():

print(name)

importでpymongoモジュールを呼び出します。その後、clientという変数を定義し、その中でpymongo.MongoClient()を用います。括弧内には、MongoDBAtlasに接続するためのコードが必要となりますので、MongoDB Atlas Database(https://www.mongodb.com/atlas/database)にアクセスし、「Sign In(サインイン)」する必要があります。

Sign In(サインイン)後、右側メニューから「DEPLOYMENT」の「Database」を選択します。選択すると、今回はMongoDBAtlasのアカウントを作成し、無料(FREE)のデータベース「Cluster0」がすでに作成されていますので、こちらに接続するために、「Connect」ボタンをクリックします。ちなみにこのデータベースの中身には何も入っていません。

クリックすると、「Connect to Cluster0」というウインドウが表示され、「Choose a connection method(接続方法を選択してください)」と書かれていますので、「Connect your application(アプリケーションを接続する)」を選択します。

選択すると、「Select your driver and version(ドライバーとバージョンを選択してください)」と書かれていますので、DRIVERを「Python」に選択し、VERSIONをお使いのVERSIONに選択します。

選択後、「Add your connection string into your application code(接続文字列をアプリケーションコードに追加します)」と書かれた箇所にコードが発行されますので、コードを編集し、コピーして、スクリプトのpymongo.MongoClient()の括弧内に貼り付けます。なお、「mongodb+srv://admin:<password>@cluster0.cywla.mongodb.net/myFirstDatabase?retryWrites=true&w=majority」となっており、「<>」の部分は削除し、MongoDB Atlas Database(https://www.mongodb.com/atlas/database)サインイン後の右側メニューの「SECURITY」の「Database Access」の「Database Users」の接続権限があるUserの「Password」を入力します。

C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\cryptography\x509\base.py:531: CryptographyDeprecationWarning: Parsed a negative serial number, which is disallowed by RFC 5280.

return rust_x509.load_pem_x509_certificate(data)

Traceback (most recent call last):

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 1278, in _get_socket

sock_info = self.sockets.popleft()

IndexError: pop from an empty deque

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "py_m_db.py", line 3, in <module>

for name in client.list_database_names():

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\mongo_client.py", line 1918, in list_database_names

for doc in self.list_databases(session, nameOnly=True)]

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\mongo_client.py", line 1899, in list_databases

res = admin._retryable_read_command(cmd, session=session)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\database.py", line 755, in _retryable_read_command

return self.__client._retryable_read(

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\mongo_client.py", line 1464, in _retryable_read

with self._slaveok_for_server(read_pref, server, session,

File "C:\Program Files\Python38\lib\contextlib.py", line 113, in __enter__

return next(self.gen)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\mongo_client.py", line 1309, in _slaveok_for_server

with self._get_socket(server, session, exhaust=exhaust) as sock_info:

File "C:\Program Files\Python38\lib\contextlib.py", line 113, in __enter__

return next(self.gen)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\mongo_client.py", line 1246, in _get_socket

with server.get_socket(

File "C:\Program Files\Python38\lib\contextlib.py", line 113, in __enter__

return next(self.gen)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 1231, in get_socket

sock_info = self._get_socket(all_credentials)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 1281, in _get_socket

sock_info = self.connect(all_credentials)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 1197, in connect

sock_info.check_auth(all_credentials)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 793, in check_auth

self.authenticate(credentials)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 810, in authenticate

auth.authenticate(credentials, self)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\auth.py", line 673, in authenticate

auth_func(credentials, sock_info)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\auth.py", line 591, in _authenticate_default

return _authenticate_scram(credentials, sock_info, 'SCRAM-SHA-1')

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\auth.py", line 333, in _authenticate_scram

res = sock_info.command(source, cmd)

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\pool.py", line 683, in command

return command(self, dbname, spec, slave_ok,

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\network.py", line 159, in command

helpers._check_command_response(

File "C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\pymongo\helpers.py", line 164, in _check_command_response

raise OperationFailure(errmsg, code, response, max_wire_version)

pymongo.errors.OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}

Passwordに「<>」をつけたままだと、上記のエラーが発生し、接続できません。

貼り付けた後、for文を用いて、データベースに接続した後にlist_database_names()を用いてlistでデータベース名を取得し、取得したものをprint()で全て出力します。

■実行・検証

このスクリプトを「py_m_db.py」という名前で、Pythonが実行されている作業ディレクトリ(カレントディレクトリ)に保存し、コマンドプロンプトから実行してみます。

C:\Users\user_\AppData\Roaming\Python\Python38\site-packages\cryptography\x509\base.py:531: CryptographyDeprecationWarning: Parsed a negative serial number, which is disallowed by RFC 5280.

return rust_x509.load_pem_x509_certificate(data)

admin

local

実行してみると、上記のように、データベースへの接続が行われて中の情報を出力させることができました。