文档型数据库MongoDB环境一键部署实战

                                              作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

一.MongoDB概述

1.MongoDB介绍

MongoDB是由总部位于美国纽约的上市公司MongoDB Inc基于C++编写的分布式文档数据库。

之所以成为文档数据库,是因为MongoDB保存的是"JSON Document",并非一般的PDF,WORD文档。

MongoDB内部使用类似于JSON的BSON格式,内部执行引擎为JS解释器,把文档存储成BSON结构,在查询时转换为JS对象,并可以通过熟悉的JS语法来操作。

MongoDB被称为最像RDBMS的NoSQL,支持事务,锁,索引类似于MySQL。


MongoDB有两个发布版本,社区版和企业版。
	- 社区版:
		基于SSPL,一种和AGPL基本类似的开源协议。
		
	- 企业版:
		企业版是基于商业协议,需要付费使用。

官网地址:
	https://www.mongodb.com/

2.mongoDB的优劣势

如上图所示,MongoDB在2025年的排名还是相当靠前的。MongoDB主要用途如下:
	- 应用数据库,比如存储银行,保险公司流水信息,类似于oracle,MySQL海量数据处理,大数据分析。
	- 网站数据,缓存等大尺寸,低价值的数据;
	- 在高伸缩的场景,用于对象及JSON数据的存储。
	- 数据量有亿万级或者不断扩容;
	- 需要2000-3000以上的读写每秒;
	- 新应用,需求汇编,数据模型无法确定;
	- 系统需要大量的地理位置查询;
	- 需要整合多个外部数据源;
	- 需要提供最好的latency;
	- 管理的主要对象<10;
	- 系统需要99.999%的高可用;
	
主要特点如下:
	- 灵活动态的文档建模;
	-  JSON数据模型比较适合开发者;
	- 支持高可用;
	- 水平扩展可以支撑很大数据量和并发;
	- 存储空间占用相对关系型数据库会小很多;
	

缺点如下:
	- 多表关联: 仅支持Left Outer Join。
	- SQL语句支持: 查询为主,部分支持。
	- 多表原子事务: 不支持。
	- 多文档原子事务: 不支持。
	- 16MB文档大小限制,不支持中文排序。
	- 服务端JavaScript性能欠佳。

3.MySQL和MongoDB逻辑结构对比

MySQL逻辑结构 MongoDB逻辑结构
库:Database 库: Database
表: table 集合: collection
记录: record 文档: document
列: column 键: key
主键: Primary key 主键(MongoDB提供key为"_id")
字段值: value 字段值: value
MongoDB和关系型数据库最大的不同如下:
	- 1.传统数据库结构化数据,定义了表结构后,每一行的内容必须符合表结构,就是说一列的个数和类型都一样。
	- 2.文档型数据库,表中的每个文档都可以有自己独特的结构,即JSON对象都可以有自己独特的属性和值。

4.MongoDB相关工具说明

软件名 描述
mongod MongoDB数据库软件服务端
mongo|mongosh MongoDB客户端工具,管理MongoDB数据库,MongoDB 5+版本中采用mongosh来替代。
mongos MongoDB路由进程,分片环境下使用
mongodump/mongorestore 命令行数据库备份和恢复工具
mogoexport/mogoimport CVS/JSON导入与导出,主要用于不同系统间数据迁移
compass MongoDB GUI管理工具。
Ops Manager(企业版) MongoDB集群管理软件,支持对分配集群的备份和还原。
BI Connector(企业版) SQL解释器/BI套接件
MongoDB Chart(企业版) MongoDB可视化软件
Atlas(付费及免费) MongoDB云托管服务,包括永久免费云数据库。
推荐阅读:
	https://www.mongodb.com/zh-cn/docs/

5.查看系统支持的版本

如上图所示,官方是支持ubuntu系统安装的。

推荐阅读
	https://www.mongodb.com/zh-cn/docs/manual/installation/

二.MongoDB安装

1.Ubuntu安装MongoDB文档

如上图所示,我们可以直接参考管的方式安装MongoDB数据库。

推荐阅读:
	https://www.mongodb.com/zh-cn/docs/manual/tutorial/install-mongodb-on-ubuntu/	

2.二进制安装MongoDB文档

如上图所示,我们下载对应的软件包安装即可。

如下图所示,如果我们的安装包缺少对应工具,则可以直接去官网下载相应的二进制包即可。

参考链接:
	https://www.mongodb.com/zh-cn/docs/manual/tutorial/install-mongodb-on-ubuntu-tarball/
	https://www.mongodb.com/try/download/community
	https://www.mongodb.com/try/download/tools

3.一键部署MongoDB脚本

3.1 安装服务

[root@prometheus-server31 ~]# ./install-mongodb.sh i
Selecting previously unselected package mongodb-mongosh-shared-openssl3.
(Reading database ... 149227 files and directories currently installed.)
Preparing to unpack mongodb-mongosh-shared-openssl3_2.4.2_amd64.deb ...
Unpacking mongodb-mongosh-shared-openssl3 (2.4.2) ...
Setting up mongodb-mongosh-shared-openssl3 (2.4.2) ...
Processing triggers for man-db (2.10.2-1) ...
YinZhengjie's MongoDB 安装完成!                            [  OK  ]
LISTEN 0      4096         0.0.0.0:27017      0.0.0.0:*          

安装成功,欢迎使用尹正杰二进制mongoDB安装脚本,欢迎下次使用!

请运行'mongosh'命令测试能否链接MongoDB服务。

[root@prometheus-server31 ~]# 
[root@prometheus-server31 ~]# 
[root@prometheus-server31 ~]# mongosh 
Current Mongosh Log ID:	67dc41b023661a418d01337a
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.4.2
Using MongoDB:		8.0.5
Using Mongosh:		2.4.2

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

------
   The server generated these startup warnings when booting
   2025-03-21T00:26:08.583+08:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2025-03-21T00:26:09.316+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2025-03-21T00:26:09.316+08:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-03-21T00:26:09.316+08:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-03-21T00:26:09.316+08:00: We suggest setting the contents of sysfsFile to 0.
   2025-03-21T00:26:09.316+08:00: Your system has glibc support for rseq built in, which is not yet supported by tcmalloc-google and has critical performance implications. Please set the environment variable GLIBC_TUNABLES=glibc.pthread.rseq=0
   2025-03-21T00:26:09.316+08:00: vm.max_map_count is too low
   2025-03-21T00:26:09.316+08:00: We suggest setting swappiness to 0 or 1, as swapping can cause performance problems.
------

test> 
[root@prometheus-server31 ~]# 

3.2 卸载服务

[root@prometheus-server31 ~]# ./install-mongodb.sh r
Removed /etc/systemd/system/multi-user.target.wants/mongod.service.
(Reading database ... 149237 files and directories currently installed.)
Removing mongodb-mongosh-shared-openssl3 (2.4.2) ...
Processing triggers for man-db (2.10.2-1) ...
卸载成功,欢迎再次使用尹正杰二进制mongoDB安装脚本哟~
[root@prometheus-server31 ~]# 

3.3 一键部署脚本

配置文件参考:
	https://www.mongodb.com/zh-cn/docs/manual/reference/configuration-options
	

脚本代码
[root@node-exporter41 ~]# cat install-mongodb.sh 
#!/bin/bash
# email: y1053419035@qq.com
# Author: 尹正杰(yinzhengjie) Jason Yin
# Blog: https://www.cnblogs.com/yinzhengjie


MONGODB_VERSOIN=ubuntu2204-8.0.5
MONGOSH_VERSION=shared-openssl3_2.4.2
MONGODB_FILE=mongodb-linux-x86_64-${MONGODB_VERSOIN}.tgz
MONGOSH_FILE=mongodb-mongosh-${MONGOSH_VERSION}_amd64.deb
URL=https://fastdl.mongodb.org/linux/$MONGODB_FILE
MONGOSHURL=https://downloads.mongodb.com/compass/$MONGOSHURL_FILE
MONGODB_DIR=/yinzhengjie/softwares/mongodb
INSTALL_DIR=/usr/local
DOWNLOAD_DIR=./download
PORT=27017
MY_IP=`hostname -I|awk '{print $1}'`

. /etc/os-release

function color() {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}

# 检查环境及基础优化
function prepare() {
    [ -e $MONGODB_DIR -o -e $INSTALL_DIR/mongodb ] && { color  "MongoDB 数据库已安装!" 1;exit; }
    if  [ $ID = "centos" -o $ID = "rocky" ];then
        rpm -q wget  &> /dev/null || yum install -y -q wget
    elif [ $ID = "ubuntu" ];then
        dpkg -l wget &> /dev/null || apt -y install wget
    else
        color  '不支持当前操作系统!' 1
        exit
    fi
    if [ -e /etc/rc.local ];then
        echo "echo never > /sys/kernel/mm/transparent hugepage/enabled" >> /etc/rc.local
    else
        cat > /etc/rc.local <<EOF
#!/bin/bash
echo never > /sys/kernel/mm/transparent hugepage/enabled
EOF
    fi
    chmod +x /etc/rc.local   
}


# 安装MongoDB
function InstallMongodb () {
    # 检查环境
    prepare

    if [ ! -d ${DOWNLOAD_DIR} ];then
       install -d ${DOWNLOAD_DIR}
    fi
    
    # download mongoDB Server
    if [ ! -e ${DOWNLOAD_DIR}/$MONGODB_FILE ];then
        wget $URL -O ${DOWNLOAD_DIR}/$MONGODB_FILE || { color  "MongoDB 数据库文件下载失败" 1; exit; } 
    fi

    # download mongosh Client
    if [ ! -e ${DOWNLOAD_DIR}/$MONGOSH_FILE ];then
        wget $MONGOSHURL -O ${DOWNLOAD_DIR}/$MONGOSH_FILE  || { color  "mongosh 数据库文件下载失败" 1; exit; } 
    fi

    # 安装MongoDB
    id mongod &> /dev/null || useradd -m -s /bin/bash mongod
    tar xf ${DOWNLOAD_DIR}/$MONGODB_FILE -C $INSTALL_DIR
    ln -s $INSTALL_DIR/mongodb-linux-x86_64-${MONGODB_VERSOIN} $INSTALL_DIR/mongodb

    # 安装mongosh
    dpkg -i ${DOWNLOAD_DIR}/${MONGOSH_FILE}

    # 配置MongoDB环境变量及配置文件生成
    echo PATH=$INSTALL_DIR/mongodb/bin/:'$PATH' > /etc/profile.d/mongodb.sh
    . /etc/profile.d/mongodb.sh
    mkdir -p $MONGODB_DIR/{conf,data,log}
    cat > $MONGODB_DIR/conf/mongo.conf <<EOF
systemLog:
  destination: file
  path: "$MONGODB_DIR/log/mongodb.log"
  logAppend: true

storage:
  dbPath: "$MONGODB_DIR/data/"
  journal:
    commitIntervalMs: 100

processManagement:
  fork: true

net:
  port: 27017
  bindIp: 0.0.0.0
EOF
    chown -R  mongod:mongod $MONGODB_DIR/

    # 编写启动脚本
    cat > /lib/systemd/system/mongod.service <<EOF
[Unit]
Description=mongodb
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
User=mongod
Group=mongod
ExecStart=$INSTALL_DIR/mongodb/bin/mongod --config $MONGODB_DIR/conf/mongo.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=$INSTALL_DIR/bin/mongod --config $MONGODB_DIR/conf/mongo.conf --shutdown
PrivateTmp=true
# 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

    # 启动mango
    systemctl daemon-reload
    systemctl enable --now  mongod &>/dev/null
    systemctl is-active mongod.service &>/dev/null
    if [ $?  -eq 0 ];then  
        color "YinZhengjie's MongoDB 安装完成!" 0
        ss -ntl| grep ${PORT}
    else
        color "YinZhengjie's MongoDB 安装失败!" 1
        exit
    fi 

    tput setaf 3
    echo """
安装成功,欢迎使用尹正杰二进制mongoDB安装脚本,欢迎下次使用!

请运行'mongosh'命令测试能否链接MongoDB服务。
"""
    tput setaf 2


}


# 卸载MongoDB
function UninstallMongoDB(){
   systemctl disable --now mongod.service
   rm -rf $INSTALL_DIR/mongodb \
          $INSTALL_DIR/mongodb-linux-x86_64-${MONGODB_VERSOIN} \
          /lib/systemd/system/mongod.service ${MONGODB_DIR} \
          $MONGODB_DIR/data/ \
          $MONGODB_DIR/log
   dpkg -r mongodb-mongosh-shared-openssl3
    tput setaf 5
    echo "卸载成功,欢迎再次使用尹正杰二进制mongoDB安装脚本哟~"
    tput setaf 7
}

# 定义主函数
function main(){
   case $1 in
     install|i)
        InstallMongodb
        ;;
      remove|r)
        UninstallMongoDB
      ;;
     *)
       echo "Invalid parameter, Usage: $0 install(i)|remove(r)"
       ;;
   esac
}

# 向入口函数传参
main $1 
[root@node-exporter41 ~]# 

具体使用请参考我给定的压缩包:"yinzhengjie-autoInstallMongoDB.tar.gz".

posted @ 2025-03-14 23:32  尹正杰  阅读(122)  评论(0)    收藏  举报