Python连接Mongodb分片集群,只需用逗号将多个主机的ip+端口分隔,写在url中:
import sys
import pymongo
from pymongo import MongoClient
from urllib import parse
# modify your settings here
username = 'your_username'
password = 'your_password'
address_list = ['1.1.1.1:1234', '1.1.1.2:1234'] # 'ip:port'
username = parse.quote_plus(username)
password = parse.quote_plus(password)
url = f"mongodb://{username}:{password}@{','.join(address_list)}/"
client = MongoClient(url)
# ping
ret = client.admin.command('ping')['ok']
if ret:
print('ping successfully!')
else:
print('ping failed!')
sys.exit(1)