MongoDB数据库应用

一、MongoDB概述

1. 什么是MongoDB

MongoDB 是一个基于分布式文件存储的开源NoSQL数据库系统,采用文档存储模型,非常适合处理大量非结构化或半结构化数据的高性能应用。

text

复制代码
MongoDB特点:
├── 文档模型(BSON/JSON格式)
├── 动态模式(无需预定义表结构)
├── 高性能读写
├── 水平扩展能力
├── 丰富的查询语言
├── 高可用复制集
├── 分布式存储
├── 地理位置支持
└── 聚合框架

2. 核心概念对比

关系型数据库 MongoDB 说明
Database Database 数据库
Table Collection 集合/表
Row Document 文档/行
Column Field 字段/列
Index Index 索引
JOIN $lookup 表关联

3. 适用场景

text

复制代码
典型应用场景:
├── 用户画像与个性化推荐
├── 物联网数据存储
├── 游戏后端数据库
├── 社交行业应用
├── 视频直播行业
├── 移动APP位置查询
└── 内容管理系统

二、MongoDB安装

1. Linux环境安装

bash

复制代码
# 1. 导入MongoDB公钥
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -

# 2. 添加软件源(Ubuntu)
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

# 3. 更新并安装
sudo apt-get update
sudo apt-get install -y mongodb-org

# CentOS/RHEL安装
cat > /etc/yum.repos.d/mongodb-org-7.0.repo << 'EOF'
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
EOF

yum install -y mongodb-org

# 4. 启动服务
systemctl start mongod
systemctl enable mongod
systemctl status mongod

2. Docker安装

bash

复制代码
# 拉取镜像
docker pull mongo:7.0

# 运行容器
docker run -d \
    --name mongodb \
    -p 27017:27017 \
    -e MONGO_INITDB_ROOT_USERNAME=admin \
    -e MONGO_INITDB_ROOT_PASSWORD=admin123 \
    -v /data/mongo:/data/db \
    mongo:7.0

# Docker Compose方式
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
  mongodb:
    image: mongo:7.0
    container_name: mongodb
    restart: always
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin123
    volumes:
      - ./data:/data/db
      - ./backup:/backup
EOF

docker-compose up -d

3. 连接MongoDB

bash

复制代码
# Shell连接
mongosh
mongosh "mongodb://localhost:27017"
mongosh "mongodb://admin:admin123@localhost:27017"

# 指定数据库连接
mongosh --host localhost --port 27017 --username admin --password admin123 --authenticationDatabase admin

# 查看状态
mongosh --eval "db.runCommand({connectionStatus: 1})"

三、MongoDB基本操作

1. 数据库操作

javascript

复制代码
// 查看所有数据库
show dbs
show databases

// 创建/切换数据库
use mydb

// 查看当前数据库
db

// 删除数据库
db.dropDatabase()

// 查看数据库统计信息
db.stats()

2. 集合操作

javascript

复制代码
// 创建集合
db.createCollection("users")
db.createCollection("logs", { capped: true, size: 10240, max: 100 })

// 查看集合
show collections
show tables

// 删除集合
db.users.drop()

// 重命名集合
db.users.renameCollection("employees")

3. 文档插入

javascript

复制代码
// 插入单个文档
db.users.insertOne({
    name: "张三",
    age: 28,
    email: "zhangsan@example.com",
    city: "北京",
    hobbies: ["阅读", "游泳"]
})

// 插入多个文档
db.users.insertMany([
    { name: "李四", age: 32, email: "lisi@example.com", city: "上海" },
    { name: "王五", age: 25, email: "wangwu@example.com", city: "广州" }
])

// 插入返回结果
var result = db.users.insertOne({ name: "赵六", age: 30 })
result.insertedId

4. 文档查询

javascript

复制代码
// 查询所有文档
db.users.find()
db.users.find().pretty()

// 条件查询
db.users.find({ name: "张三" })
db.users.find({ age: { $gt: 25 } })      // 大于
db.users.find({ age: { $gte: 25 } })     // 大于等于
db.users.find({ age: { $lt: 30 } })      // 小于
db.users.find({ age: { $lte: 30 } })     // 小于等于
db.users.find({ age: { $ne: 25 } })      // 不等于

// 多条件查询
db.users.find({ age: { $gte: 25, $lte: 35 }, city: "北京" })

// IN查询
db.users.find({ city: { $in: ["北京", "上海"] } })

// OR查询
db.users.find({ $or: [{ city: "北京" }, { age: { $lt: 25 } }] })

// 正则查询
db.users.find({ name: /^张/ })

// 查询单个文档
db.users.findOne({ name: "张三" })

// 投影(指定返回字段)
db.users.find({}, { name: 1, age: 1, _id: 0 })

// 排序
db.users.find().sort({ age: 1 })    // 升序
db.users.find().sort({ age: -1 })   // 降序

// 分页
db.users.find().skip(10).limit(5)

// 计数
db.users.countDocuments()
db.users.countDocuments({ age: { $gt: 25 } })

// 去重
db.users.distinct("city")

5. 文档更新

javascript

复制代码
// 更新单个文档
db.users.updateOne(
    { name: "张三" },
    { $set: { age: 29, city: "深圳" } }
)

// 更新多个文档
db.users.updateMany(
    { city: "北京" },
    { $set: { city: "上海" } }
)

// 替换文档
db.users.replaceOne(
    { name: "张三" },
    { name: "张三", age: 30, email: "new@example.com" }
)

// 自增操作
db.users.updateOne(
    { name: "张三" },
    { $inc: { age: 1 } }
)

// 数组操作
db.users.updateOne(
    { name: "张三" },
    { $push: { hobbies: "跑步" } }
)

db.users.updateOne(
    { name: "张三" },
    { $pull: { hobbies: "游泳" } }
)

// 更新或插入(upsert)
db.users.updateOne(
    { name: "李四" },
    { $set: { age: 25, city: "深圳" } },
    { upsert: true }
)

// 返回更新后的文档
db.users.findOneAndUpdate(
    { name: "张三" },
    { $set: { age: 31 } },
    { returnDocument: "after" }
)

6. 文档删除

javascript

复制代码
// 删除单个文档
db.users.deleteOne({ name: "张三" })

// 删除多个文档
db.users.deleteMany({ age: { $lt: 18 } })

// 删除所有文档
db.users.deleteMany({})

// 返回删除的文档
db.users.findOneAndDelete({ name: "李四" })

四、索引操作

1. 创建索引

javascript

复制代码
// 单字段索引
db.users.createIndex({ name: 1 })      // 升序
db.users.createIndex({ age: -1 })      // 降序

// 唯一索引
db.users.createIndex({ email: 1 }, { unique: true })

// 复合索引
db.users.createIndex({ city: 1, age: -1 })

// 多键索引(数组字段)
db.users.createIndex({ hobbies: 1 })

// 文本索引
db.users.createIndex({ description: "text" })

// 地理空间索引
db.places.createIndex({ location: "2dsphere" })

// 哈希索引(分片用)
db.users.createIndex({ _id: "hashed" })

// 后台创建索引
db.users.createIndex({ name: 1 }, { background: true })

2. 索引管理

javascript

复制代码
// 查看索引
db.users.getIndexes()

// 删除索引
db.users.dropIndex("name_1")
db.users.dropIndexes()

// 重建索引
db.users.reIndex()

// 隐藏索引(MongoDB 4.4+)
db.users.createIndex({ age: 1 }, { hidden: true })

3. 索引使用分析

javascript

复制代码
// 查看查询使用索引情况
db.users.find({ name: "张三" }).explain("executionStats")

// 强制使用索引
db.users.find({ name: "张三" }).hint({ name: 1 })

// 查看索引大小
db.users.stats().indexSizes

五、聚合框架

1. 聚合管道基础

javascript

复制代码
// 聚合管道语法
db.collection.aggregate([
    { $match: { ... } },   // 过滤
    { $group: { ... } },   // 分组
    { $sort: { ... } },    // 排序
    { $project: { ... } }, // 投影
    { $limit: ... },       // 限制
    { $skip: ... },        // 跳过
    { $unwind: ... },      // 展开数组
    { $lookup: ... }       // 关联查询
])

2. 常用聚合阶段

javascript

复制代码
// $match - 过滤文档
db.orders.aggregate([
    { $match: { status: "completed", amount: { $gt: 100 } } }
])

// $group - 分组统计
db.orders.aggregate([
    { $group: {
        _id: "$category",
        totalAmount: { $sum: "$amount" },
        avgAmount: { $avg: "$amount" },
        maxAmount: { $max: "$amount" },
        minAmount: { $min: "$amount" },
        count: { $sum: 1 }
    }}
])

// $project - 字段投影
db.users.aggregate([
    { $project: {
        fullName: { $concat: ["$firstName", " ", "$lastName"] },
        age: 1,
        _id: 0
    }}
])

// $sort - 排序
db.orders.aggregate([
    { $sort: { createdAt: -1, amount: -1 } }
])

// $limit 和 $skip
db.users.aggregate([
    { $sort: { age: -1 } },
    { $skip: 10 },
    { $limit: 5 }
])

// $unwind - 展开数组
db.users.aggregate([
    { $unwind: "$hobbies" },
    { $group: { _id: "$hobbies", count: { $sum: 1 } } }
])

// $lookup - 关联查询(左连接)
db.orders.aggregate([
    { $lookup: {
        from: "users",
        localField: "userId",
        foreignField: "_id",
        as: "userInfo"
    }}
])

// $addFields - 添加字段
db.users.aggregate([
    { $addFields: {
        isAdult: { $gte: ["$age", 18] }
    }}
])

3. 聚合表达式

javascript

复制代码
// 算术表达式
{ $add: ["$price", "$tax"] }
{ $subtract: ["$total", "$discount"] }
{ $multiply: ["$price", "$quantity"] }
{ $divide: ["$total", "$count"] }
{ $mod: ["$number", 10] }

// 字符串表达式
{ $concat: ["$firstName", " ", "$lastName"] }
{ $toLower: "$name" }
{ $toUpper: "$name" }
{ $substr: ["$text", 0, 5] }

// 条件表达式
{ $cond: { if: { $gte: ["$age", 18] }, then: "Adult", else: "Minor" } }
{ $ifNull: ["$nickname", "$name"] }

// 数组表达式
{ $size: "$hobbies" }
{ $arrayElemAt: ["$tags", 0] }

4. 聚合示例

javascript

复制代码
// 示例1:统计各城市用户平均年龄
db.users.aggregate([
    { $group: {
        _id: "$city",
        avgAge: { $avg: "$age" },
        userCount: { $sum: 1 }
    }},
    { $sort: { userCount: -1 } }
])

// 示例2:订单统计报表
db.orders.aggregate([
    { $match: { status: "completed", createdAt: { $gte: ISODate("2024-01-01") } } },
    { $group: {
        _id: { month: { $month: "$createdAt" }, year: { $year: "$createdAt" } },
        totalAmount: { $sum: "$amount" },
        orderCount: { $sum: 1 }
    }},
    { $sort: { "_id.year": 1, "_id.month": 1 } },
    { $project: {
        year: "$_id.year",
        month: "$_id.month",
        totalAmount: 1,
        orderCount: 1,
        _id: 0
    }}
])

// 示例3:用户行为分析
db.events.aggregate([
    { $match: { eventType: "click", timestamp: { $gte: ISODate("2024-01-01") } } },
    { $group: {
        _id: { userId: "$userId", page: "$page" },
        clickCount: { $sum: 1 },
        lastClick: { $max: "$timestamp" }
    }},
    { $sort: { clickCount: -1 } },
    { $limit: 100 }
])

六、副本集配置

1. 副本集架构

text

复制代码
副本集架构图:

┌─────────────────────────────────────────┐
│              副本集名称: rs0            │
├─────────────────────────────────────────┤
│                                         │
│    ┌─────────┐     ┌─────────┐         │
│    │ Primary │────→│Secondary│         │
│    │  (主)   │     │  (从)   │         │
│    └────┬────┘     └────┬────┘         │
│         │               │              │
│         ↓               ↓              │
│    ┌─────────┐     ┌─────────┐         │
│    │Secondary│     │ Arbiter │         │
│    │  (从)   │     │ (仲裁)  │         │
│    └─────────┘     └─────────┘         │
└─────────────────────────────────────────┘

2. 副本集配置

bash

复制代码
# 1. 配置mongod.conf
cat > /etc/mongod.conf << 'EOF'
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 0.0.0.0

replication:
  replSetName: rs0

processManagement:
  fork: true
  pidFilePath: /var/run/mongod.pid
EOF

# 2. 启动所有节点
systemctl restart mongod

# 3. 初始化副本集(在主节点执行)
mongosh

rs.initiate({
    _id: "rs0",
    members: [
        { _id: 0, host: "192.168.1.10:27017" },
        { _id: 1, host: "192.168.1.11:27017" },
        { _id: 2, host: "192.168.1.12:27017", arbiterOnly: true }
    ]
})

# 4. 查看副本集状态
rs.status()
rs.conf()
rs.isMaster()

3. 副本集管理

javascript

复制代码
// 添加节点
rs.add("192.168.1.13:27017")
rs.add({ host: "192.168.1.13:27017", priority: 2 })

// 添加仲裁节点
rs.addArb("192.168.1.14:27017")

// 移除节点
rs.remove("192.168.1.13:27017")

// 重新配置
var cfg = rs.conf()
cfg.members[0].priority = 3
rs.reconfig(cfg)

// 主节点降级
rs.stepDown(60)

// 冻结节点(阻止成为主节点)
rs.freeze(120)

// 允许从节点读取
db.getMongo().setReadPref("secondaryPreferred")

七、分片集群配置

1. 分片集群架构

text

复制代码
分片集群架构:

┌─────────────────────────────────────────┐
│           客户端应用程序                  │
└─────────────────┬───────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│            Mongos路由节点                │
└─────────────────┬───────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│           Config Server                 │
│        (存储元数据,3节点副本集)          │
└─────────────────┬───────────────────────┘
                  ↓
┌─────────────────────────────────────────┐
│              分片集群                    │
├─────────────┬─────────────┬─────────────┤
│  Shard 1    │  Shard 2    │  Shard 3    │
│  (副本集)   │  (副本集)   │  (副本集)   │
└─────────────┴─────────────┴─────────────┘

2. 分片配置步骤

bash

复制代码
# 1. 配置Config Server(3节点)
mongod --configsvr --replSet configReplSet --port 27019 --dbpath /data/config

# 初始化Config副本集
mongosh --port 27019
rs.initiate({
    _id: "configReplSet",
    configsvr: true,
    members: [
        { _id: 0, host: "192.168.1.10:27019" },
        { _id: 1, host: "192.168.1.11:27019" },
        { _id: 2, host: "192.168.1.12:27019" }
    ]
})

# 2. 配置Shard节点(每个分片是副本集)
mongod --shardsvr --replSet shard1 --port 27018 --dbpath /data/shard1

# 3. 启动Mongos路由节点
mongos --configdb configReplSet/192.168.1.10:27019,192.168.1.11:27019,192.168.1.12:27019 --port 27017 --bind_ip 0.0.0.0

# 4. 添加分片
mongosh --port 27017
sh.addShard("shard1/192.168.1.20:27018")
sh.addShard("shard2/192.168.1.21:27018")
sh.addShard("shard3/192.168.1.22:27018")

3. 分片管理

javascript

复制代码
// 启用数据库分片
sh.enableSharding("mydb")

// 集合分片(使用哈希分片键)
sh.shardCollection("mydb.users", { _id: "hashed" })

// 集合分片(使用范围分片键)
sh.shardCollection("mydb.orders", { orderId: 1 })

// 创建分片索引
db.users.createIndex({ _id: "hashed" })

// 查看分片状态
sh.status()
sh.getBalancerState()

// 开启/关闭均衡器
sh.setBalancerState(true)
sh.setBalancerState(false)

// 查看分片分布
db.users.getShardDistribution()

// 查看分片键
db.users.getShardKeyDistribution()

八、备份与恢复

1. 备份方法

bash

复制代码
# 1. mongodump备份(逻辑备份)
# 全库备份
mongodump --host localhost --port 27017 --username admin --password admin123 --authenticationDatabase admin --out /backup/full_$(date +%Y%m%d)

# 单数据库备份
mongodump --db mydb --out /backup/mydb_$(date +%Y%m%d)

# 单集合备份
mongodump --db mydb --collection users --out /backup/users_$(date +%Y%m%d)

# 压缩备份
mongodump --db mydb --archive=/backup/mydb_$(date +%Y%m%d).gz --gzip

# 2. 文件系统快照备份(物理备份)
# 需先锁定数据库
mongosh --eval "db.fsyncLock()"
cp -r /var/lib/mongodb /backup/mongodb_$(date +%Y%m%d)
mongosh --eval "db.fsyncUnlock()"

2. 恢复方法

bash

复制代码
# 1. mongorestore恢复
# 恢复全库
mongorestore --host localhost --port 27017 --username admin --password admin123 --authenticationDatabase admin /backup/full_20240101

# 恢复指定数据库
mongorestore --db mydb /backup/mydb_20240101/mydb

# 恢复指定集合
mongorestore --db mydb --collection users /backup/users_20240101/mydb/users.bson

# 从压缩文件恢复
mongorestore --archive=/backup/mydb_20240101.gz --gzip

# 2. 文件系统恢复
# 停止MongoDB
systemctl stop mongod
# 恢复数据文件
cp -r /backup/mongodb_20240101/* /var/lib/mongodb/
# 启动MongoDB
systemctl start mongod

3. 备份脚本

bash

复制代码
#!/bin/bash
# mongodb_backup.sh - MongoDB自动备份脚本

BACKUP_DIR="/backup/mongodb"
DATE=$(date +%Y%m%d_%H%M%S)
MONGO_HOST="localhost"
MONGO_PORT="27017"
MONGO_USER="admin"
MONGO_PASS="admin123"
RETENTION_DAYS=7

# 创建备份目录
mkdir -p $BACKUP_DIR/{full,daily,logs}

# 日志函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $BACKUP_DIR/logs/backup.log
}

# 全量备份
full_backup() {
    log "开始全量备份..."
    mongodump --host $MONGO_HOST --port $MONGO_PORT \
        --username $MONGO_USER --password $MONGO_PASS \
        --authenticationDatabase admin \
        --out $BACKUP_DIR/full/full_$DATE
    if [ $? -eq 0 ]; then
        log "全量备份成功: full_$DATE"
        # 压缩备份
        tar -czf $BACKUP_DIR/full/full_$DATE.tar.gz -C $BACKUP_DIR/full full_$DATE
        rm -rf $BACKUP_DIR/full/full_$DATE
    else
        log "全量备份失败"
    fi
}

# 增量备份(指定数据库)
daily_backup() {
    log "开始日常备份..."
    mongodump --host $MONGO_HOST --port $MONGO_PORT \
        --username $MONGO_USER --password $MONGO_PASS \
        --authenticationDatabase admin \
        --db mydb \
        --out $BACKUP_DIR/daily/daily_$DATE
    if [ $? -eq 0 ]; then
        log "日常备份成功: daily_$DATE"
    else
        log "日常备份失败"
    fi
}

# 清理旧备份
cleanup() {
    log "清理 $RETENTION_DAYS 天前的备份..."
    find $BACKUP_DIR/full -name "full_*.tar.gz" -mtime +$RETENTION_DAYS -delete
    find $BACKUP_DIR/daily -type d -name "daily_*" -mtime +$RETENTION_DAYS -exec rm -rf {} \;
    log "清理完成"
}

# 主函数
main() {
    log "================== 备份开始 =================="
    
    if [ $(date +%w) -eq 0 ]; then
        full_backup
    else
        daily_backup
    fi
    
    cleanup
    log "================== 备份结束 =================="
}

main

九、性能优化

1. 查询优化

javascript

复制代码
// 1. 使用explain分析查询
db.users.find({ name: "张三", age: { $gt: 25 } }).explain("executionStats")

// 关键指标
// - totalKeysExamined: 索引扫描数
// - totalDocsExamined: 文档扫描数
// - executionTimeMillis: 执行时间
// - stage: 查询阶段

// 2. 创建合适的索引
db.users.createIndex({ name: 1, age: -1 })

// 3. 使用投影减少返回字段
db.users.find({ name: "张三" }, { name: 1, age: 1, _id: 0 })

// 4. 使用limit限制返回数量
db.users.find().limit(100)

// 5. 避免使用skip跳过大量数据
// 不好的写法
db.users.find().skip(10000).limit(10)
// 好的写法
db.users.find({ _id: { $gt: lastId } }).limit(10)

2. 写入优化

javascript

复制代码
// 1. 批量写入
db.users.insertMany([
    { name: "用户1", age: 20 },
    { name: "用户2", age: 21 },
    // ... 更多文档
], { ordered: false })  // ordered: false 允许无序插入,提高性能

// 2. 使用bulkWrite批量操作
db.users.bulkWrite([
    { insertOne: { document: { name: "用户1" } } },
    { updateOne: { filter: { name: "用户2" }, update: { $set: { age: 25 } } } },
    { deleteOne: { filter: { name: "用户3" } } }
])

// 3. 调整写入关注度
db.users.insertOne({ name: "测试" }, { writeConcern: { w: 1, j: false } })

3. 配置优化

yaml

复制代码
# mongod.conf 优化配置
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
    commitIntervalMs: 100
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4           # 缓存大小(物理内存的50%-70%)
      directoryForIndexes: true
    collectionConfig:
      blockCompressor: snappy   # 压缩算法:snappy/zlib/zstd
    indexConfig:
      prefixCompression: true

operationProfiling:
  mode: slowOp                # 慢查询模式
  slowOpThresholdMs: 100      # 慢查询阈值(毫秒)

net:
  maxIncomingConnections: 10000
  compression:
    responders: snappy

replication:
  oplogSizeMB: 2048           # Oplog大小(MB)

processManagement:
  fork: true

4. 性能监控

javascript

复制代码
// 查看数据库状态
db.stats()
db.serverStatus()

// 查看集合统计
db.users.stats()

// 查看当前操作
db.currentOp()

// 终止慢操作
db.killOp(opid)

// 查看索引使用情况
db.users.aggregate([
    { $indexStats: {} }
])

// 查看锁状态
db.serverStatus().locks

// 查看连接数
db.serverStatus().connections

// 查看内存使用
db.serverStatus().mem

// 查看WiredTiger缓存
db.serverStatus().wiredTiger.cache

5. 监控脚本

bash

复制代码
#!/bin/bash
# mongodb_monitor.sh - MongoDB监控脚本

MONGO_HOST="localhost"
MONGO_PORT="27017"
MONGO_USER="admin"
MONGO_PASS="admin123"

# 获取监控数据
get_metrics() {
    mongosh --quiet --host $MONGO_HOST --port $MONGO_PORT \
        --username $MONGO_USER --password $MONGO_PASS \
        --authenticationDatabase admin <<EOF
        var stats = db.serverStatus();
        var repl = db.isMaster();
        
        print("timestamp," + new Date().toISOString());
        print("connections," + stats.connections.current);
        print("opcounters_insert," + stats.opcounters.insert);
        print("opcounters_query," + stats.opcounters.query);
        print("opcounters_update," + stats.opcounters.update);
        print("opcounters_delete," + stats.opcounters.delete);
        print("mem_resident," + stats.mem.resident);
        print("mem_virtual," + stats.mem.virtual);
        print("ismaster," + repl.ismaster);
EOF
}

# 告警检查
check_alerts() {
    CONN=$(mongosh --quiet --eval "db.serverStatus().connections.current" \
        --username $MONGO_USER --password $MONGO_PASS --authenticationDatabase admin)
    
    if [ $CONN -gt 8000 ]; then
        echo "警告: 连接数过高 - $CONN"
    fi
}

get_metrics
check_alerts

十、MongoDB优缺点分析

1. 核心优势

优势 说明
灵活的文档模型 无需预定义表结构,动态添加字段
高性能横向扩展 通过分片集群实现线性扩展
丰富的查询能力 完整的CRUD操作和聚合管道
强大的地理空间支持 内置GeoJSON格式,支持高效地理查询

2. 局限与挑战

局限 说明
事务支持有限 多文档事务仅限副本集,性能衰减明显
内存消耗大 需要充足内存保证性能
复杂查询能力 某些SQL特性(如递归查询)表达困难
运维复杂度 分片键选择、副本集选举等需经验

3. 适用场景建议

场景 推荐度 说明
实时分析 ★★★★ 日志分析、用户行为追踪
内容管理 ★★★★ 多形态数据存储
物联网 ★★★★ 设备状态数据流处理
敏捷开发 ★★★★ 快速迭代产品原型
金融核心交易 ★☆☆ 建议使用关系型数据库

十一、总结

MongoDB核心要点

text

复制代码
□ 文档模型
  □ BSON格式存储
  □ 动态模式
  □ 嵌套文档支持

□ 高可用架构
  □ 副本集自动故障转移
  □ 读写分离
  □ 数据冗余

□ 水平扩展
  □ 分片集群
  □ 自动数据均衡
  □ 线性扩展能力

□ 性能优化
  □ 索引策略
  □ 聚合管道
  □ 查询优化

常用命令速查

操作 命令
连接 mongosh
查看数据库 show dbs
切换数据库 use dbname
查看集合 show collections
插入文档 db.collection.insertOne()
查询文档 db.collection.find()
更新文档 db.collection.updateOne()
删除文档 db.collection.deleteOne()
创建索引 db.collection.createIndex()
聚合查询 db.collection.aggregate()
相关推荐
梦想的颜色2 小时前
mongoTemplate + Java 增删改查基础介绍
数据结构·数据库·mysql
小小小米粒3 小时前
redis命令集合
数据库·redis·缓存
herinspace3 小时前
管家婆实用贴-如何分离和附加数据库
开发语言·前端·javascript·数据库·语音识别
步辞4 小时前
Go语言怎么用channel做信号通知_Go语言channel信号模式教程【完整】
jvm·数据库·python
weixin_424999364 小时前
mysql行级锁失效的原因排查_检查查询条件与执行计划
jvm·数据库·python
Polar__Star4 小时前
uni-app怎么实现App端一键换肤 uni-app全局样式动态切换【实战】
jvm·数据库·python
南境十里·墨染春水5 小时前
linux学习进展 进程间通讯——共享内存
linux·数据库·学习
斯维赤6 小时前
Python学习超简单第八弹:连接Mysql数据库
数据库·python·学习
Chuer_6 小时前
讲透财务Agent核心概念,深度拆解财务Agent应用趋势
大数据·数据库·安全·数据分析·甘特图