新建配置文件 config.ini
[db]
DB_USER = test_db
DB_PASSWORD = XXX6778a
新建配置文件 mongo_config.ini
import configparser
def getConfig(dbkey):
Config = configparser.ConfigParser()
Config.read("config.ini")
value = Config.get("db", dbkey)
return value;
新建demo.py
from pymongo import MongoClient
import mongo_config
#连接MongoDB数据库
DB_USER=mongo_config.getConfig('DB_USER')
DB_PASSWORD=mongo_config.getConfig('DB_PASSWORD')
client = MongoClient('10.18.12.209', 27018)
db = client.matrix_db
db.authenticate(DB_USER, DB_PASSWORD)
myset = db.neo.thirdparty.account.AccountEntity
for item in myset.find():
print(item)
最开始遇到报错:ModuleNotFoundError: No module named 'pymongo'
sudo pip uninstall pymongo ==> Succesfully uninstalled
sudo pip uninstall bson ==> Cannot uninstall requirement bson, not installed
sudo apt-get remove python-bson ==> sudo: apt-get: command not found
sudo apt-get remove python-gridfs # not sure if it's necessary ==> sudo: apt-get: command not found
sudo pip install pymongo -U ==> successfully installed pymongo