Python3: MongoDB のデータを作成 (Create)

参考ページ
[PythonでMongoDBを操作する（PyMongo）](https://python-work.com/pymongo/)
[SCRAM-SHA-256 (RFC 7677)](https://pymongo.readthedocs.io/en/stable/examples/authentication.html#scram-sha-256-rfc-7677)

## ライブラリーのインストール

Ubuntu 23.10 にインストール

```bash
sudo apt install python3-pymongo
sudo apt install python3-dotenv
```

## プログラム

フォルダー構造

```text
$ tree -a
.
├── .env
├── config_mariadb.py
└── mongo_create.py
```

```py:mongo_create.py
#! /usr/bin/python
#
#	mongo_create.py
#
#					Mar/01/2023
#
# -------------------------------------------------------------
import sys
import pymongo
#
from config_mariadb import config_mariadb_proc
#
# -------------------------------------------------------------
def dict_to_mongo_proc(db_aa,collection,dict_aa):
#
	db_aa[collection]
#	db_aa[collection].remove ()
	db_aa[collection].drop()
#
	for key in dict_aa.keys():
		unit = dict_aa[key]
		db_aa[collection].insert_one({"key": key,"name": unit['name'],"population": unit['population'],"date_mod": unit['date_mod']})
#
# -------------------------------------------------------------
def dict_append_proc(dict_aa,key,name,population,date_mod):
	dict_aa[key] = {'name':name,'population':population,'date_mod':date_mod}
#
	return dict_aa
#
# -------------------------------------------------------------
def	data_prepare_proc():
	dict_aa = {} 
#
	dict_aa = dict_append_proc(dict_aa,'t1161','さいたま',52913,'2003-8-20')
	dict_aa = dict_append_proc(dict_aa,'t1162','所沢',17465,'2003-2-10')
	dict_aa = dict_append_proc(dict_aa,'t1163','越谷',91654,'2003-7-14')
	dict_aa = dict_append_proc(dict_aa,'t1164','久喜',53672,'2003-9-9')
	dict_aa = dict_append_proc(dict_aa,'t1165','熊谷',42391,'2003-8-4')
	dict_aa = dict_append_proc(dict_aa,'t1166','秩父',35187,'2003-1-21')
	dict_aa = dict_append_proc(dict_aa,'t1167','川越',81946,'2003-7-23')
	dict_aa = dict_append_proc(dict_aa,'t1168','和光',29714,'2003-10-16')
	dict_aa = dict_append_proc(dict_aa,'t1169','新座',41823,'2003-12-25')
#
	return	dict_aa
#
# -------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
host,user,password,data_base = config_mariadb_proc()
collection='saitama'
dict_aa = data_prepare_proc()
#
try:
	client = pymongo.MongoClient(host,username=user,password=password,
			authSource=data_base,authMechanism='SCRAM-SHA-256')
	db = client[data_base]
#
	dict_to_mongo_proc(db,collection,dict_aa)
except Exception as ee:
	sys.stderr.write("*** error *** in MongoClient ***\n")
	sys.stderr.write(str(ee) + "\n")
#
sys.stderr.write("*** 終了 ***\n")
# -------------------------------------------------------------
```

```py:config_mariadb.py
#! /usr/bin/python
#
#	config_mariadb.py
#
#					Feb/22/2023
# --------------------------------------------------------
import os
from dotenv import load_dotenv
#
# --------------------------------------------------------
def config_mariadb_proc():
	dotenv_path = '.env'
	load_dotenv(dotenv_path)
	host = os.environ.get("host")
	user = os.environ.get("user")
	password = os.environ.get("password")
	data_base = os.environ.get("data_base")
#
	return	host,user,password,data_base
# --------------------------------------------------------
```

```text:.env
host='localhost'
user='scott'
password='tiger123'
data_base='city'
```

## 実行結果

```text
$ ./mongo_create.py
*** 開始 ***
*** 終了 ***
```

## 確認したバージョン

```text
$ python
Python 3.10.9 (main, Dec 19 2022, 17:35:49) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> print(pymongo.__version__)
4.3.3
```