MongDB安装配置基础使用
内容概述
主要用途:
-
应用数据库,比如:存储银行,保险公司流水信息,类似于0racle,MySQL海量数据处理,大数据分析
-
网站数据、缓存等大尺寸、低价值的数据
-
在高伸缩性的场景,用于对象及ISON数据的存储。
主要特点
-
灵活动态的文档建模
-
JSON数据模型比较适合开发者
-
支持高可用
-
水平扩展可以支撑很大数据量和并发
-
存储空间占用相对关系型数据库会小很多
缺点:
-
多表关联:仅仅支持Left OuterJoin
-
SQL语句支持:查询为主,部分支持
-
多表原子事务: 不支持
-
多文档原子事务:不支持
-
16MB 文档大小限制,不支持中文排序
-
服务端 Javascript 性能欠佳
1)安装 MongDB
Ubuntu2204
下载地址:https://www.mongodb.com/try/download/community
安装方法:https://www.mongodb.com/zh-cn/docs/manual/installation/
1.1)二进制安装包安装(7.0.17)
root@mongdb-1:~# cat install_mongodb.sh
#
#********************************************************************
#Author: tanghao
#QQ: 2826588067
#Date: 2025-02-19
#Filename: install_mongodb.sh
#URL: https://www.stangj.com
#Description: The test script
#Copyright (C): 2025 All rights reserved
#********************************************************************
MONGODB_VERSOIN=ubuntu2204-7.0.17
#MONGODB_VERSOIN=rhel70-5.0.3
MONGODB_FILE=mongodb-linux-x86_64-${MONGODB_VERSOIN}.tgz
URL=https://fastdl.mongodb.org/linux/$MONGODB_FILE
MONGODB_DIR=/mongodb
INSTALL_DIR=/apps
PORT=27017
MY_IP=`hostname -I|awk '{print $1}'`
mkdir -p $INSTALL_DIR
. /etc/os-release
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
}
system_prepare () {
[ -e $MONGODB_DIR -o -e $INSTALL_DIR/mongodb ] && { color "MongoDB 数据库已安装!" 1;exit; }
if [ $ID = "centos" -o $ID = "rocky" ];then
rpm -q curl &> /dev/null || yum install -y -q curl
elif [ $ID = "ubuntu" ];then
dpkg -l curl &> /dev/null || apt -y install curl
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
echo never > /sys/kernel/mm/transparent hugepage/enabled
EOF
fi
chmod +x /etc/rc.local
}
mongodb_file_prepare () {
if [ ! -e $MONGODB_FILE ];then
curl -O $URL || { color "MongoDB 数据库文件下载失败" 1; exit; }
fi
}
install_mongodb () {
id mongod &> /dev/null || useradd -m -s /bin/bash mongod
tar xf $MONGODB_FILE -C $INSTALL_DIR
ln -s $INSTALL_DIR/mongodb-linux-x86_64-${MONGODB_VERSOIN} $INSTALL_DIR/mongodb
#mongod --dbpath $db_dir --bind_ip_all --port $PORT --logpath $db_dir/mongod.log --fork
}
config_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:
# enabled: true # mongdb 7 需要注释这两行
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/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
systemctl daemon-reload
systemctl enable --now mongod &>/dev/null
}
start_mongodb() {
systemctl is-active mongod.service &>/dev/null
if [ $? -eq 0 ];then
echo
color "MongoDB 安装完成!" 0
else
color "MongoDB 安装失败!" 1
exit
fi
}
system_prepare
mongodb_file_prepare
install_mongodb
config_mongodb
start_mongodb
2.)客户端连接
2.1)终端工具
https://www.mongodb.com/try/download/shell
root@mongdb-1:/apps# wget https://downloads.mongodb.com/compass/mongosh-2.4.0-linux-x64.tgz
root@mongdb-1:/apps# tar xf mongosh-2.4.0-linux-x64.tgz
root@mongdb-1:/apps# mongosh-2.4.0-linux-x64/bin/mongosh
Current Mongosh Log ID: 67c5bd9c16481cc2d651e943
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.4.0
Using MongoDB: 7.0.17
Using Mongosh: 2.4.0
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
The server generated these startup warnings when booting
2025-03-03T22:15:50.477+08:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
2025-03-03T22:15:51.232+08:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
2025-03-03T22:15:51.232+08:00: vm.max_map_count is too low
------
test>
2.2)GUI工具
https://www.mongodb.com/try/download/compass
3)MongoDB管理
3.1)通过python插入数据
root@mongdb-1:~# apt install python3-pip
root@mongdb-1:~# pip3 install pymongo
root@mongdb-1:~# cat test_mongodb.py
from pymongo import MongoClient
# 客户端连接
client = MongoClient('mongodb://127.0.0.1:27017')
# 指定数据库 # Database类
db = client['test']
# 集合 # Collection类
students = db['students']
for i in range(10):
student = {'id':i, 'name':'tang' + str(i), 'age':20}
result = students.insert_one(student)
print(result)
client.close()
root@mongdb-1:~# chmod +x test_mongodb.py
root@mongdb-1:~# ./test_mongodb.py
3.2)CRUD
https://www.mongodb.com/zh-cn/docs/manual/tutorial/insert-documents/
test> show dbs # 查看数据库
admin 40.00 KiB
config 108.00 KiB
local 40.00 KiB
test 40.00 KiB
# 进入数据库
test> use test
# 查看表
test> show tables
students
# 查看 students 表所有数据
test> db.students.find()
[
{
_id: ObjectId('67c5c33fe670f9fd51ca50d2'),
id: 0,
name: 'tang0',
age: 20
},
{
_id: ObjectId('67c5c33fe670f9fd51ca50d3'),
id: 1,
name: 'tangj1',
age: 20
},
...
# 查询 students 表 id = 9 的数据
test> db.students.find({id:9}).pretty()
[
{
_id: ObjectId('67c5c33fe670f9fd51ca50db'),
id: 9,
name: 'wang9',
age: 20
}
]
#修改文档,如果没有加mu1ti:true.默认只修改第一个符合条件的文档
test> db.students.update({id:1},{$set:{age:30}},{multi: true})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
test> db.students.find({id:1}).pretty()
[
{
_id: ObjectId('67c5c33fe670f9fd51ca50d3'),
id: 1,
name: 'tangj1',
age: 30
}
]
# 删余指定的文档 id = 1
test> db.students.remove({id:1})
DeprecationWarning: Collection.remove() is deprecated. Use deleteOne, deleteMany, findOneAndDelete, or bulkWrite.
{ acknowledged: true, deletedCount: 1 }
test> db.students.find().limit(3)
[
{
_id: ObjectId('67c5c33fe670f9fd51ca50d2'),
id: 0,
name: 'tangj0',
age: 20
},
{
_id: ObjectId('67c5c33fe670f9fd51ca50d4'),
id: 2,
name: 'tangj2',
age: 20
},
{
_id: ObjectId('67c5c33fe670f9fd51ca50d5'),
id: 3,
name: 'tangj3',
age: 20
}
]
#删除集合中所有记录,但表还存在
test>db.students.remove({})
#查看集合存储信息,包括集合中素引和数据压缩存储后的大小
test> db.students.totalSize()
3.3)用户和权限管理
https://www.mongodb.com/zh-cn/docs/manual/tutorial/create-users/
3.3.1)关于用户验证库
-
创建用户时,use所在的库就是此用户的验证库
-
登录时,必须明确指定验证库才能登录
-
一个数据库可以成为多个用户的验证库,但一个用户只能使用一个验证库
-
对于管理员用户,必须在admin下创建,即管理员用的验证库是admin
-
普通用户的验证库一般是所管理的库
-
如果直接登录到数据库,不进行use,默认的验证库是test
-
从3.6版本开始,配置文件中不添加bindlp参数,默认不允许远程登录,只能本地管理员登录
3.3.2)开启用户认证
#注意:启用认证后,仍然可以直接登录,但无权限做数据操作,但可以创建用户
#方法1:命令行方式通过“--auth”参数
mongod --auth --port 27017 --dbpath /data/db
#方法2,修改配置文件中,加入以下配置
root@mongdb-1:~# cat >> /mongodb/conf/mongo.conf<<EOF
security:
authorization: enabled
EOF
root@mongdb-1:~# systemctl restart mongod.service
注意: 启动了用户认证 没有用户就没有权限查询数据
test> show databases
test>
3.3.3)用户管理说明
用户的创建,需要基于指定数据库,即用户是存放于特定数据库的,即验证库
#创建用户
use <db> #切换至需要创建用户的验证库后,再创建用户
db.createUser{
user:"<name>",
pwd:"<cleartext password>"
roles:[{ role:"<role>,
db :"<database>"}|"<role>",
....
}
#基本语法说明:
user:用户名
pwd:密码
roles:
ro1e:角色名,比如:root,readwrite,read
db:上面角色作用的数据库对象
#验证用户
use <验证库>
db.auth('用户名','密码')
#用户保存在admin库的users集合中
use admin
db.system.users.find()
#登录验证
mongosh -u 用户名 -p 密码 <验证库>
mongosh -u用户名 -p 密码 <MongoDB主机IP>/<验证库>
#修改密码
db.changeUserPassword("用户名","新密码"”)
#删除用户
use <验证库>
db.dropUser("用户名")
范例: 创建管理用户
#创建超级管理源用户
test> use admin
admin> db.createUser({user: "root",pwd:"123456",roles: [{role: "root", db: "admin" }]})
# 验证用户
root@mongdb-1:/apps/mongosh-2.4.0-linux-x64/bin# ./mongosh -u root -p 123456 admin
root@mongdb-1:/apps/mongosh-2.4.0-linux-x64/bin# ./mongosh -u root -p 123456 192.168.139.161:27017/admin
admin> show dbs
admin 132.00 KiB
config 108.00 KiB
local 72.00 KiB
test 72.00 KiB
#在admin库中system.users表中查看用户列表
test> use admin
admin> db.system.users.find().pretty()
[
{
_id: 'admin.root',
userId: UUID('4e741cfa-d71b-46bb-aa40-ecd2726cf571'),
user: 'root',
db: 'admin',
credentials: {
'SCRAM-SHA-1': {
iterationCount: 10000,
salt: 'EMrTc4ZpR+waAM4zY/1Nzg==',
storedKey: 'Gbgkvj+B7vdwvvhVy7zJLKaTZiA=',
serverKey: 'cbyL2zUuEev5RrqEx7pdAl2snD0='
},
'SCRAM-SHA-256': {
iterationCount: 15000,
salt: 'Eg/LGBlJjii6TyPRUmf9DNGYQuYkBVyUxSqjRA==',
storedKey: 'ghpk92IqUecHCb3JX+9bs0aPrkP5NNza/b/OoF1gZNI=',
serverKey: 'mKq8B10j0BMeoclqV71zfcMoQkA8xTrXIE5fWLQ3oz0='
}
},
roles: [ { role: 'root', db: 'admin' } ]
}
]
范例: 创建普通用户
# 创建普通用户
admin> use test
test> db.createUser(
{
user: "myTester",
pwd: "123456",
roles: [ { role: "read", db: "test" },
{ role: "readWrite", db: "reporting" } ]
}
)
# 验证用户
root@mongdb-1:/apps/mongosh-2.4.0-linux-x64/bin# ./mongosh -u root -p 123456 admin
root@mongdb-1:/apps/mongosh-2.4.0-linux-x64/bin# ./mongosh -u myTester -p 123456 192.168.139.161:27017/test
# 验证权限
test> show dbs
test 72.00 KiB # 只能看到 test 数据库
test> db.students.find().limit(2) # 正常查询
[
{
_id: ObjectId('67c5c33fe670f9fd51ca50d2'),
id: 0,
name: 'wang0',
age: 20
},
{
_id: ObjectId('67c5c33fe670f9fd51ca50d4'),
id: 2,
name: 'wang2',
age: 20
}
]
test> db.students.updateOne({id:1},{$set:{age:40}}) # 修改失败 权限拒绝
MongoServerError[Unauthorized]: not authorized on test to execute command { update: "students", updates: [ { q: { id: 1 }, u: { $set: { age: 40 } } } ], ordered: true, lsid: { id: UUID("72a5c230-3f5b-4ff4-83ed-ef1c30a54aba") }, $db: "test" }
文章评论