pymongo のインストール
sudo apt install python3-pymongo
Docker 上の MongoDB のインストール
docker run --name my-mongo -d -p 27017:27017 mongo:latest
動いていることを確認
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
df5f71e30ee8 mongo:latest "docker-entrypoint.s…" 17 minutes ago Up 16 minutes 0.0.0.0:27017->27017/tcp, :::27017->27017/tcp my-mongo
Python のプログラム
create_authors.py
#! /usr/bin/python
from pymongo import MongoClient
# MongoDB コンテナに接続
client = MongoClient('mongodb://localhost:27017/')
# データベースの選択
db = client['my_database']
# コレクションの選択
collection = db['my_collection']
# データの挿入
data = {'name': '森鴎外', 'birth': 1862}
collection.insert_one(data)
data = {'name': '夏目漱石', 'birth': 1867}
collection.insert_one(data)
data = {'name': '島崎藤村', 'birth': 1872}
collection.insert_one(data)
# データの取得
results = collection.find()
for unit in results:
print(unit)
実行結果
$ ./create_authors.py
{'_id': ObjectId('667bc79bed08fc9849ad4941'), 'name': '森鴎外', 'birth': 1862}
{'_id': ObjectId('667bc79bed08fc9849ad4942'), 'name': '夏目漱石', 'birth': 1867}
{'_id': ObjectId('667bc79bed08fc9849ad4943'), 'name': '島崎藤村', 'birth': 1872}
mongosh で確認
$ docker exec -it my-mongo bash
root@df5f71e30ee8:/# mongosh
(省略)
test>
test> show dbs
admin 40.00 KiB
config 108.00 KiB
local 40.00 KiB
my_database 40.00 KiB
test> use my_database
switched to db my_database
my_database> show collections
my_collection
my_database> db.my_collection.find()
[
{
_id: ObjectId('667bc79bed08fc9849ad4941'),
name: '森鴎外',
birth: 1862
},
{
_id: ObjectId('667bc79bed08fc9849ad4942'),
name: '夏目漱石',
birth: 1867
},
{
_id: ObjectId('667bc79bed08fc9849ad4943'),
name: '島崎藤村',
birth: 1872
}
]
my_database>
コンテナーの起動
コンテナーの名前をしらべる
docker container ls -a
コンテナの起動
docker start my-mongo
起動していることを確認
docker ps