为什么使用pymongo访问mongodb的数据之前需要校验库名和表名,因为pymongo不会帮忙校验,写错库名,它会默认新建一个新数据库,因此需要校验,校验代码如下:
from pymongo import MongoClient
def check_mongodb(db_name, collection):
# connection
db_client = MongoClient('mongodb://user_name:password@ip:port/')
database_names = db_client.list_database_names()
if db_name not in database_names:
raise ValueError('db_name is not exists, please check database name')
else:
db = db_client[db_name]
collection_names = db.list_collection_names()
if collection not in collection_names:
raise ValueError('collection is not exists, please check collection name')
else:
return True
return