当前位置: 首页 > 工具软件 > PyMongo > 使用案例 >

【Python】pymongo使用

宋正真
2023-12-01

官方文档:http://api.mongodb.com/python/current/index.html

MongoReplicaSetClient:http://api.mongodb.com/python/current/api/pymongo/mongo_replica_set_client.html

mongo文档:https://docs.mongodb.com/manual/reference/command/

pymongo可以使用mongo command方法调用mongo方法

from pymongo import MongoClient
c = MongoClient("10.207.0.128:4000")
admin = c["admin"]
#获取实例状态
admin.command('serverStatus')
#副本集角色降级
admin.command("replSetStepDown",10)

from pymongo import MongoReplicaSetClient
#连接副本集
r= MongoReplicaSetClient(host = , port = , replicaSet = )
connection_admin=r.admin
connection_admin.authenticate('name','#') #获取副本集主节点从节点 r.primary r.secondaries

 

获得库对象和集合对象分别有两种方法:

db = client.test_database
# 或者
db = client['test-database']
得到一个数据集合:

collection = db.test_collection
# 或者
collection = db['test-collection']

 

 

连接认证 auth failed解决方法

注意MongoDB3.0版本以后采用的是'SCRAM-SHA-1'认证方式,pymongo需要更新2.8以上版本

http://api.mongodb.com/python/current/examples/authentication.html

 

mongo副本集rs.status()中

state:https://docs.mongodb.com/manual/reference/replica-states/

其他:https://docs.mongodb.com/manual/reference/command/replSetGetStatus/#dbcmd.replSetGetStatus

 

pymongo链接副本集读写分离和负载均衡的使用:

http://api.mongodb.com/python/current/examples/high_availability.html

 

from pymongo import MongoClient,ReadPreference
client = MongoClient(['host1:port','host2:port','host3:port'], replicaset='replset_name', readPreference='secondaryPreferred')
db_name = client.get_database('db_name',read_preference=ReadPreference.NEAREST)
db_name.authenticate('username','passwd',mechanism='SCRAM-SHA-1')

 

 

查询MongoDB有哪些库,库大小:

https://docs.mongodb.com/manual/reference/command/listDatabases/#dbcmd.listDatabases

admin.command("listDatabases",1)

command是库级别的,库、集合、副本集等操作要按照语法:

db_object.command({'command-name':'command-value'})
例如
db_test.command({ 'collStats' : 'collection-test})

 

posted on 2016-12-21 14:27 poorX 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jiangxu67/p/6207586.html

 类似资料: