【Python】pymongo使用

官方文档: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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值