經(jīng)過幾番折騰,現(xiàn)在終于可以用pymongo連接上mongoDB數(shù)據(jù)庫,并且能正常插入數(shù)據(jù),現(xiàn)做記錄如下:
系統(tǒng)環(huán)境是:CentOS 7
通過源碼方式安裝的 MongoDB數(shù)據(jù)庫扎附,具體安裝過程參考下面的連接:
https://zhuanlan.zhihu.com/p/50240932
在這個安裝過程中,配置文件中的data后面沒有db目錄结耀。在data目錄下新建db目錄后留夜,修改配置文件如下:
dbpath=/opt/mongoDB/mongodbserver/data/db
logpath=/opt/mongoDB/mongodbserver/log/mongodb.log
port=27017
fork=true
journal=false
storageEngine=mmapv1
auth=true
重新啟動mongoDB:
service mongod restart
登錄mongoDB數(shù)據(jù)庫,執(zhí)行下面命令:
mongo
use admin;
重新創(chuàng)建用戶图甜,提示Successfully added user:碍粥,表示創(chuàng)建成功:
db.createUser({user:"michael",pwd:"michael123",roles:[{role:"root",db:"admin"}]});
此時可用創(chuàng)建的用戶登錄數(shù)據(jù)庫,登錄成功就返回1:
db.auth("michael", "michael123");
現(xiàn)在可以寫一個Python程序來操作mongoDB數(shù)據(jù)庫黑毅,以測試是否成功嚼摩,python代碼如下:
from pymongo import MongoClient
host = 'mongodb://michael:michael123@localhost:27017/'
client = MongoClient(host)
db = client.test # 指定數(shù)據(jù)庫
collection = db.students # 指定集合
res = collection.insert({"name":"michael", "age":20}) # 插入數(shù)據(jù),返回一個id值
print(res)
最后輸出ID號表示成功:5c6fb47bf3721d3445bd09bf