windows下mongodb設(shè)置用戶名密碼&用python連接
本文博客鏈接:http://blog.csdn.net/jdh99,作者:jdh,轉(zhuǎn)載請(qǐng)注明.
環(huán)境:
主機(jī):WIN10
python版本:3.5
mongodb版本:3.4.2
開(kāi)發(fā)環(huán)境:pyCharm
mongodb設(shè)置用戶名密碼:編寫(xiě)mongodb配置文件mongodb.confdbpath=F:/test/db1logpath=F:/test/log/mongodb.loglogappend=truebind_ip=127.0.0.1port=27019#fork=truemaster=trueauth=false注意:設(shè)置用戶名密碼前將auth參數(shù)設(shè)置為false在命令行窗口運(yùn)行mongodb服務(wù)器輸入命令:mongod -f f:/test/mongodb.conf在命令行窗口運(yùn)行shell界面配置用戶名密碼注意:直接輸入mongo連接數(shù)據(jù)庫(kù)默認(rèn)ip是127.0.01,端口是270717輸入命令:mongo.exe mongodb://localhost:27019在shell界面配置賬號(hào)管理員root,利用此賬號(hào)可以增加其他賬號(hào)注意:賬號(hào)管理員沒(méi)有讀寫(xiě)的權(quán)限,只能增加其他賬號(hào)輸入命令:use admin輸入命令:db.createUser({user:"root",pwd:"root",roles:[{"role":"userAdminAnyDatabase","db":"admin"}]}) 在shell界面給數(shù)據(jù)庫(kù)db1增加賬號(hào)jdh11:輸入命令登陸賬號(hào)管理員:db.auth("root", "root")輸入命令:db.createUser({user:"jdh11",pwd:"123456",roles:[{"role":"readWrite","db":"db1"}]})權(quán)限說(shuō)明:userAdminAnyDatabase 有分配角色和用戶的權(quán)限,沒(méi)有讀寫(xiě)的權(quán)限r(nóng)oot 超級(jí)管理員readWrite 有讀寫(xiě)權(quán)限r(nóng)ead 有讀權(quán)限重新運(yùn)行mongodb服務(wù)器將mongodb.conf中的auth設(shè)置為true輸入命令:mongod -f f:/test/mongodb.conf重新運(yùn)行shell:輸入命令:mongo.exe mongodb://localhost:27019測(cè)試賬號(hào)是否成功:輸入命令切換到db1數(shù)據(jù)庫(kù):use db1輸入show collections,彈出錯(cuò)誤:> show collections2017-02-11T13:18:46.524+0800 E QUERY [thread1] Error: listCollections failed: { "ok" : 0, "errmsg" : "not authorized on db1 to execute command { listCollections: 1.0, filter: {} }", "code" : 13, "codeName" : "Unauthorized"} :_getErrorWithCode@src/mongo/shell/utils.js:25:13DB.PRototype._getCollectionInfosCommand@src/mongo/shell/db.js:805:1DB.prototype.getCollectionInfos@src/mongo/shell/db.js:817:19DB.prototype.getCollectionNames@src/mongo/shell/db.js:828:16shellHelper.show@src/mongo/shell/utils.js:748:9shellHelper@src/mongo/shell/utils.js:645:15@(shellhelp2):1:1登陸賬號(hào):注意:要切換到admin數(shù)據(jù)庫(kù)登陸,完整登陸流程:> use adminswitched to db admin> db.auth("jdh11", "123456")1> use db1switched to db db1> show collectionscol>用python連接mongodb數(shù)據(jù)庫(kù)配置數(shù)據(jù)庫(kù)參數(shù)代碼:HOST = '0.0.0.0'PORT = 12800DATABASE_IP = '127.0.0.1'DATABASE_PORT = 27019DATABASE_NAME = 'db1'連接代碼:
from pymongo import MongoClientfrom config import *client = MongoClient(DATABASE_IP, DATABASE_PORT)db_auth = client.admindb_auth.authenticate("jdh11", "123456")db = client[DATABASE_NAME]collection = db.colprint(list(collection.find({'name': 'jdh11'})))參考鏈接:MongoDB 教程Mongodb 3.2 開(kāi)啟密碼認(rèn)證 Python數(shù)據(jù)庫(kù)-鏈接mongodb帶用戶驗(yàn)證Tutorial
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注