MongoDB 是一个基于分布式文件存储的开源文档数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB保存的是“JSON Document”,内部使用类似于Json的bson格式。内部执行引擎为JS解释器。把文档存储成bson结构,在查询时转换为JS对象,并可以通过熟悉的js语法来操作。MongoDB被称为最像RDBMS 的NoSQL,支持事务,锁,索引类似于MySQL。

  • MongoDB 官网地址:https://www.mongodb.com/
  • MongoDB 各平台下载地址:https://www.mongodb.com/download-center#community

MongoDB的安装也很简单,官方针对不同的系统均提供了包安装以及二进制安装指导文档

  • 官网安装包:https://www.mongodb.com/try/download/community
  • CentOS安装官方文档:https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-red-hat/
  • Ubuntu安装官方文档:https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/

以二进制为例,安装一个单节点的Mongodb

系统基础配置

创建mongodb用户
groupadd mongod; useradd -g mongod -s /sbin/nologin -r mongod
内核参数优化
cat >> /etc/rc.local << EOF
echo never > /sys/kernel/mm/transparent_hugepage/enabled 
EOF
chmod +x /etc/rc.local 
CentOS安装,关闭防火墙,关闭SElinux
yum -y install libcurl openssl xz-libs
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-6.0.3.tgz
tar -zxf mongodb-linux-x86_64-rhel70-6.0.3.tgz -C /usr/local/src/
ln -sv /usr/local/src/mongodb-linux-x86_64-rhel70-6.0.3 /usr/local/mongodb
Ubuntu安装
sudo apt-get -y install libcurl4 openssl liblzma5
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu2004-6.0.3.tgz
tar -zxf mongodb-linux-x86_64-ubuntu2004-6.0.3.tgz -C /usr/local/src/
ln -sv /usr/local/src/mongodb-linux-x86_64-ubuntu2004-6.0.3 /usr/local/mongodb
配置环境变量 
echo "export PATH=\$PATH:/usr/local/mongodb/bin" >> /etc/profile
source /etc/profile
mkdir -p /usr/local/mongodb/{conf,data,log}
cat > /usr/local/mongodb/conf/mongod.conf  <<EOF
# where to write logging data. 
systemLog:
  destination: file
  logAppend: true
  path: /usr/local/mongodb/log/mongod.log
# Where and how to store data.
storage:
  dbPath: /usr/local/mongodb/data
  journal:
    enabled: true
# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /usr/local/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo
# 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.
# 开启认证,如不需认证可注释以下两行
security:	
  authorization: enabled
EOF
chown -R mongod:mongod /usr/local/src/mongodb-linux-x86_64-ubuntu2004-6.0.3 /usr/local/mongodb

启动、关闭 Mongodb

启动mongodb
mongod -f /usr/local/mongodb/conf/mongod.conf 
about to fork child process, waiting until server is ready for connections.
forked process: 83599
child process started successfully, parent exiting
ps -ef|grep mongod
mongod   22570   1 14 16:12 ?   00:00:01 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongod.conf
netstat -anptu|grep mongod
tcp   0   0 0.0.0.0:27017    0.0.0.0:*    LISTEN   22570/mongod
关闭mongodb
mongod -f /usr/local/mongodb/conf/mongod.conf --shutdown

安装客户端连接工具mongosh,官网下载地址:https://www.mongodb.com/try/download/shell

wget https://downloads.mongodb.com/compass/mongosh-1.6.2-linux-x64.tgz
tar -zxf mongosh-1.6.2-linux-x64.tgz -C /usr/local/src/
cp /usr/local/src/mongosh-1.6.2-linux-x64/bin/mongosh* /usr/local/mongodb/bin/
source /etc/profile
连接mongodb
mongosh    # mongosh --host 192.168.5.124  连接远程mongodb
Current Mongosh Log ID:	63c751c4c8a1a522debcc5c4
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.2
Using MongoDB:		6.0.3
Using Mongosh:		1.6.2
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
以下报错表示需要验证用户
test> show dbs
MongoServerError: command listDatabases requires authentication

创建 mongod.service 文件

cat > /usr/lib/systemd/system/mongod.service  <<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network-online.target
Wants=network-online.target
[Service]
User=mongod
Group=mongod
Environment="OPTIONS=-f /usr/local/mongodb/conf/mongod.conf"
ExecStart=/usr/local/mongodb/bin/mongod \$OPTIONS
PermissionsStartOnly=true
PIDFile=/usr/local/mongodb/mongod.pid
Type=forking
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false
# Recommended limits for mongod as specified in
# https://docs.mongodb.com/manual/reference/ulimit/#recommended-ulimit-settings
[Install]
WantedBy=multi-user.target
EOF
启动mongodb
chown -R mongod:mongod /usr/local/src/mongodb-linux-x86_64-ubuntu2004-6.0.3 /usr/local/mongodb
systemctl daemon-reload 
systemctl start mongod.service; systemctl enable mongod.service
systemctl status mongod.service 
ps -ef|grep mongod
mongod   22570   1 14 16:12 ?   00:00:01 /usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongod.conf
netstat -anptu|grep mongod
tcp   0   0 0.0.0.0:27017    0.0.0.0:*    LISTEN   22570/mongod

MongoDB数据库默认是没有用户名及密码的,即无权限访问限制。为了方便数据库的管理和安全,应启用认证和创建数据库用户。用户验证库有以下几点

  1. 创建用户时,use所在的库就是此用户的验证库;
  2. 登录时,必须明确指定验证库才能登录;
  3. 一个数据库可以成为多个用户的验证库,但一个用户只能使用一个验证库;
  4. 对于管理员用户,必须在admin下创建,即管理员用的验证库是admin;
  5. 普通用户的验证库一般是所管理的库;
  6. 如果直接登录到数据库,不进行use,默认的验证库是test;
  7. 从3.6版本开始,配置文件中不添加bindIp参数,默认不允许远程登录,只能本地管理员登录
  8. 官方文档:https://docs.mongodb.com/manual/tutorial/create-users/

MongoDB内置角色说明

  1. root:只在admin数据库中可用。超级账号,超级权限
  2. read:允许用户读取指定非系统数据库
  3. readWrite:允许用户读写指定非系统数据库
  4. dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
  5. userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
  6. clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
  7. readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
  8. readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
  9. userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
  10. dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
创建用户,用户的创建,需要基于指定数据库,即用户是存放于特定数据库的,即验证库
创建普通用户之前,需要切换到admin库,创建一个管理员账户,然后用管理员用户登陆
use admin
switched to db admin
admin> db.createUser ( {user: "root",pwd: "root123",roles: [{role: "root", db: "admin"}]})
{ ok: 1 }
mongosh -u root -p root123 admin    # 用管理员登陆
admin> use test
switched to db test
test> db.createUser ( {user: "testu",pwd: "testuser",roles: [{role: "readWrite", db: "test"}]})
{ ok: 1 }

test> db.getUsers()
{
  users: [
    {
      _id: 'test.testu',
      userId: new UUID("29bfc2fc-9c14-4eb2-b0fb-1cead4b10123"),
      user: 'testu',
      db: 'test',
      roles: [ { role: 'readWrite', db: 'test' } ],
      mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
    }
  ],
  ok: 1
}
普通用户登陆
mongosh -u testu -p testuser test
test> db.students_info.insert ({name: " hlro"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("63c6037b9c1ffae4f712d488") }
}
test> show tables
students_info
admin> use stu_info
switched to db stu_info
stu_info> stu_info> db.createUser ( {user: "stu",pwd: "12345678",roles: [{role: "readWrite", db: "stu_info"}, {role: "read", db: "test"}]})