2.5.6 Centos7下安装MongoDB4.4

1、查看防火墙状态

systemctl status firewalld.service

2、解压安装包,并移动目录

tar -zxvf mongodb-linux-x86_64-rhel70-4.4.1.tgz
mv mongodb-linux-x86_64-rhel70-4.4.1 MongoDB

3、进入目录,创建Data文件夹和日志文件夹

cd MongoDB
mkdir -p ./data/db
mkdir ./log

4、编辑配置文件vi mongod.conf,可以放在MongoDB的bin目录下或者MongoDB的安装目录下,配置文件内容如下

systemLog:
   destination: file
   path: "/usr/local/MongoDB/log/mongod.log"
   logAppend: true
storage:
   dbPath: "/usr/local/MongoDB/data/db"
   journal:
      enabled: true
processManagement:
   fork: true
net:
   bindIp: 0.0.0.0
   port: 27017

注意:配置文件如果内容不正确会导致mongodb服务起不起来,mongodb的配置文件要求k:v这种形式的:后面必须接空格并且文件中不能有tab缩进,必须是空格缩进。

配置保存后,在bin目录下,使用命令:mongod -f /usr/local/MongoDB/mongod.conf  或  mongod --config /usr/local/MongoDB/mongod.conf 启动服务,出现successfully即证明服务成功启动

5、把mongodb添加到环境变量中,把下面这一段添加到/etc/profile文件末尾或者在/etc/profile.d文件夹下新建一个文件mongodb.sh然后把下面的写进去

#MongoDB ENVIRONMENT
export PATH=$PATH:/usr/local/MongoDB/bin

# 在/etc/profile中添加

source /etc/profile

 # 在/etc/profile.d/mongodb.sh

source /etc/profile.d/mongodb.sh

 6、配置mongodb服务

cd /lib/systemd/system/
vi mongodb.service

配置如下:

[Unit]  
Description=mongodb  
After=network.target remote-fs.target nss-lookup.target  

[Service]  
Type=forking  
ExecStart=/usr/local/MongoDB/bin/mongod --config /usr/local/MongoDB/mongod.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/usr/local/MongoDB/bin/mongod --shutdown --config /usr/local/MongoDB/mongod.conf
PrivateTmp=true

[Install]  
WantedBy=multi-user.target

7、mongodb命令

#启动服务
systemctl start mongodb.service    
#停止服务
systemctl stop mongodb.service
#添加开机自启动
systemctl enable mongodb.service
#重启服务
systemctl restart mongodb.service
#查看服务状态
systemctl status mongodb.service  

8、登录MongoDB,创建账号并授权

mongodb
use admin;

给admin数据库添加管理员用户名和密码,用户名和密码请自行设置

db.createUser({user:"admin",pwd:"123",roles:["root"]});

创建数据库,并创建对应的账号密码

use testDB;

db.createUser({

user: "test",
pwd: "test@123",
roles:[
{role:"readWrite", db:"testDB"},
{role: "dbAdmin", db:"testDB"},
]
})

验证账号密码是否正确

db.auth("admin","123");
db.auth("test","test@123");
原文地址:https://www.cnblogs.com/duyao/p/14547277.html