Linux Centos 7安装MongoDB

配置yum源

创建并编辑文件/etc/yum.repos.d/mongodb-org-4.2.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

字段说明:

name         # 名称
baseurl      # 获得下载的路径
gpkcheck=1   # 表示对从这个源下载的rpm包进行校验;
enable=1     # 表示启用这个源。
gpgkey       # gpg验证

使用yum安装MongoDB

yum install -y mongodb-org

验证安装结果

rpm -qa |grep mongodb
rpm -ql mongodb-org-server

Linux Centos 7安装MongoDB_第1张图片

启动MongoDB

service mongod start   或者  systemctl start mongod.service   // 启动
service mongod restart   // 重启
service mongod stop    // 关闭

sudo yum erase $(rpm -qa | grep mongodb-org)    # 卸载MongoDB
sudo rm -r /var/log/mongodb  # 删除日志文件
sudo rm -r /var/lib/mongo    # 删除数据文件

修改配置文件mongodb.conf

vi /etc/mongod.conf

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

重启

service mongod restart 

远程连接

mongo ip:27017

连接到自定义的用户

创建用户,设置账号,密码,权限

// 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文件,启用身份验证

vi /etc/mongod.conf

security:
  authorization: "enabled"   # disable or enabled

重启MongoDB

service mongod restart 

用户认证

> use admin
switched to db admin
> db.auth("root", "123456")
1 // 授权成功

远程连接


// 终端连接
mongo ip:27017/database -u username -p password

// mongoose方式连接
mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});

你可能感兴趣的:(mongodb)