1.創建文件
在/etc/yum.repos.d
目錄下創建mongodb-org.repo
的一個文件,文件內寫入:
[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
2.執行如下命令:
sudo yum install -y mongodb-org
3.啓動命令
systemctl start mongod
systemctl enable mongod #設置開機啓動
4.開放遠程連接Mongodb
打開mongo的配置文件
vim /etc/mongod.conf
修改bindIp的值爲0.0.0.0
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0
重啓mongo服務
systemctl restart mongod
5.創建用戶
鍵入mongo進入mongo終端:
#創建用戶,設置賬號,密碼,權限
#// admin數據庫
> use admin
switched to db admin
> db.createUser({ user:"root", pwd:"123456", roles:["root"] })
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
#// 其他數據庫
> use test
switched to db test
> db.createUser({ user:"admin", pwd:"123456", roles:["readWrite", "dbAdmin"] })
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
修改mongodb.conf文件,啓用身份驗證
vim /etc/mongod.conf
security:
authorization: "enabled" # disable or enabled
重啓服務:systemctl restart mongod
6.登錄
用戶認證
> use admin
switched to db admin
> db.auth("root", "123456")
1 // 授權成功
複製代碼// 其他常用命令
db.updateUser(user, writeConcern) # 更新用戶
db.dropUser('test') # 刪除用戶
複製代碼
遠程連接
// 終端連接
mongo 10.128.218.14:27017:27017/database -u username -p password
// mongoose方式連接
mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});