python連接mongodb集羣 cluster

網上資料比較少,自己測試了下。
連接方法如下:

import pymongo
db = pymongo.MongoClient('mongodb://10.18.6.46,10.18.6.26,10.18.6.102')

上面默認的端口do都是27017,如果是其他端口,需要這樣修改:

db = pymongo.MongoClient('mongodb://10.18.6.46:8888,10.18.6.26:9999,10.18.6.102:7777')

然後就可以正常讀寫數據庫:
 
讀:
coll=db['testdb']['testcollection'].find()
for i in coll:
    print(i)

輸出內容:

{'_id': ObjectId('5cf4c7981ee9edff72e5c503'), 'username': 'hello'}
{'_id': ObjectId('5cf4c7991ee9edff72e5c504'), 'username': 'hello'}
{'_id': ObjectId('5cf4c7991ee9edff72e5c505'), 'username': 'hello'}
{'_id': ObjectId('5cf4c79a1ee9edff72e5c506'), 'username': 'hello'}
{'_id': ObjectId('5cf4c7b21ee9edff72e5c507'), 'username': 'hello world'}


 
寫:

collection = db['testdb']['testcollection']

for i in range(10):
    collection.insert({'username':'huston{}'.format(i)})


 
原創文章,轉載請註明出處:
http://30daydo.com/article/494

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章