windows下mongodb設置用戶名密碼&用python連接
本文博客鏈接:http://blog.csdn.net/jdh99,作者:jdh,轉載請註明.
環境:
主機:WIN10
python版本:3.5
mongodb版本:3.4.2
開發環境:pyCharm
- 編寫mongodb配置文件mongodb.conf
dbpath=F:\test\db1
logpath=F:\test\log\mongodb.log
logappend=true
bind_ip=127.0.0.1
port=27019
#fork=true
master=true
auth=false
- 在命令行窗口運行mongodb服務器
- 在命令行窗口運行shell界面配置用戶名密碼
- 在shell界面配置賬號管理員root,利用此賬號可以增加其他賬號
- 在shell界面給數據庫db1增加賬號jdh11:
root 超級管理員
readWrite 有讀寫權限
read 有讀權限
- 重新運行mongodb服務器
- 測試賬號是否成功:
2017-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:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:805:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:817:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:828:16
shellHelper.show@src/mongo/shell/utils.js:748:9
shellHelper@src/mongo/shell/utils.js:645:15
@(shellhelp2):1:1
switched to db admin
> db.auth("jdh11", "123456")
1
> use db1
switched to db db1
> show collections
col
>
HOST = '0.0.0.0'
PORT = 12800
DATABASE_IP = '127.0.0.1'
DATABASE_PORT = 27019
DATABASE_NAME = 'db1'
連接代碼:
from pymongo import MongoClient
from config import *
client = MongoClient(DATABASE_IP, DATABASE_PORT)
db_auth = client.admin
db_auth.authenticate("jdh11", "123456")
db = client[DATABASE_NAME]
collection = db.col
print(list(collection.find({'name': 'jdh11'})))