設置 MongoDB 數據庫的用戶名和密碼
/etc/xxx.conf
編輯 mongodb 配置文件啓用用戶驗證
vim /etc/mongodb.conf
# IP
bind_ip = 0.0.0.0
# 端口
port = 27017
修改以下安全配置
# Turn on/off security. Off is currently the default
#noauth = true
#auth = true
去掉 #auth=true
前的註釋 #
auth = true
重啓 mongodb
服務
service mongodb restart
使用 mongo
shell 連接服務器
# 連接服務器
mongo
# 連接到 admin 數據庫
use admin
# 創建管理員賬號,用戶名和密碼可以任意,角色爲 `root`
db.createUser({user:'root',pwd:'123456',roles:['root']})
# 登錄
db.auth('root','123456')
登錄後在 admin 數據庫
user admin
db.auth('root','hello')
show collections
> system.users
> system.version
# 顯示用戶信息
db.system.users.find().pretty()
爲特定的某個數據庫設計用戶名和密碼
# 創建數據庫
use hr
# 創建用戶
db.createUser({
user:'hr_user',
pwd:'123',
roles:[{db:'hr',role:'dbOwner'}]
})
# 顯示用戶
show users
連接數據庫
mongo 127.0.0.1:27017/demo -u demo -p
# 獲得 mongo shell 更多信息
mongo --help
數據建模
文檔
中嵌入子文檔
- 文檔之間
引用
($lookup
類似關係數據庫中的表連接)
MongoDB 一個文檔不能超過 16M(一個文檔不要嵌套過大)
MongoDB GridFS(網格文件系統)
用於存儲大文件(超過 16M),文件(默認)會被切成 255k 的塊存儲,存儲在兩個集合中,一個存儲文件的元信息,另一個存儲文件的數據
# 往數據庫 myfile 中上傳(put)文件
mongofiles -d myfile put 文件路徑
# 顯示數據庫 myfile 中的文件
mongofiles -d myfile list
文件存儲在兩個集合中
- fs.files 文件的元數據信息(文件名、大小、塊大小、日期、_id)
- fs.chunks 文件的內容(files_id, 內容,格式)
mongofiles
上傳到遠程數據庫
mongofiles -h ip -d db_name -u user -p password put file_path
mongofiles -h ip -d db_name -u user -p password list
mongofiles
工具是命令行的開發工具