首先,你需要使用pip
安装pymongo
包,然后使用以下代码连接到MongoDB服务器并进行认证:
import pymongoclass MongoOperator:
def __init__(self, host, port, username, password):
# 建立MongoDB连接
self.client = pymongo.MongoClient(host=host, port=port)
# 进行认证
self.client.admin.authenticate(username, password)
其中,host
和port
是MongoDB服务器的地址和端口号,username
和password
是你的用户名和密码。
之后,你就可以使用self.client
对象来进行各种MongoDB操作了。例如,获取数据库列表可以使用self.client.list_database_names()
,获取某个数据库的集合列表可以使用self.client[db_name].list_collection_names()
,插入文档可以使用self.client[db_name][collection_name].insert_one(doc)
等。
有关MongoDB操作的更多信息,可以参考pymongo官方文档:https://pymongo.readthedocs.io/en/stable/