scene description
Usually, when using PyMongo to connect to the MongoDB database in an offline environment, it is connected to a database without a user name and password, so how to connect to a MongoDB database (online environment) with a user name and password?
code example
Option One
NOTE : This method was removed in PyMongo 4.x ! ! !
import pymongo
client = pymongo.MongoClient(host='host', port=27017)
# info_data 需要用户名和密码进行身份认证的数据库
db = client.info_data
# username:用户名;password:密码
db.authenticate('username', 'password')
print(db.list_collection_names())
Option II
import pymongo
client = pymongo.MongoClient(
# 主机
host=host,
# 端口
port=port,
# 用户名
username=username,
# 密码
password=password,
# 需要用户名和密码进行身份认证的数据库
authSource='info_data'
)
db = client.info_data
print(db.list_collection_names())
third solution
import pymongo
client = pymongo.MongoClient('mongodb://username:password@host:port/?authSource=info_data')
db = client.info_data
print(db.list_collection_names())
username: username
password: password
host: host
port: port
info_data: database that requires username and password for authentication