【Python】pymongo使用

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

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

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

pymongo能够使用mongo command方法调用mongo方法api

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解决方法spa

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

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

 

mongo副本集rs.status()中htm

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})
相关文章
相关标签/搜索