MongoDB常用代码干货

一、连接与基本操作

# 连接本地 MongoDB
mongosh

# 连接远程 MongoDB(需指定 IP 和端口)
mongosh "mongodb://192.168.1.100:27017"

# 连接带认证的 MongoDB
mongosh "mongodb://username:password@host:port/dbname?authSource=admin"

# 查看当前使用的数据库
db

# 切换/创建数据库(若不存在,插入数据后自动创建)
use testdb

# 查看所有数据库
show dbs

# 删除当前数据库
db.dropDatabase()

二、集合操作

# 创建集合(显式创建,通常无需手动创建,插入文档时自动创建)
db.createCollection("users")

# 查看当前数据库中的所有集合
show collections

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

# 重命名集合
db.oldCollectionName.renameCollection("newCollectionName")

三、文档操作(增删改查)

插入文档

# 插入单个文档
db.users.insertOne({ name: "Alice", age: 30, hobbies: ["reading", "swimming"] })

# 插入多个文档
db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
])
查询文档

# 查询集合中的所有文档
db.users.find()

# 带条件查询(查找 age 大于 30 的文档)
db.users.find({ age: { $gt: 30 } })

# 查询单个文档(返回第一个匹配结果)
db.users.findOne({ name: "Alice" })

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

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

# 分页(skip 跳过数量,limit 返回数量)
db.users.find().skip(10).limit(5)
更新文档

# 更新单个文档(将 name 为 Alice 的文档的 age 改为 31)
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31, hobbies: ["reading", "yoga"] } }
)

# 更新多个文档(将所有文档的 age 加 1)
db.users.updateMany(
  {},
  { $inc: { age: 1 } }
)

# 替换整个文档(注意:会删除原文档中未指定的字段)
db.users.replaceOne(
  { name: "Alice" },
  { name: "Alice Smith", age: 31 }
)
删除文档

# 删除单个文档(匹配到的第一个)
db.users.deleteOne({ name: "Bob" })

# 删除所有匹配的文档
db.users.deleteMany({ age: { $lt: 30 } })

# 清空集合(比 deleteMany 更高效)
db.users.deleteMany({})

四、高级查询操作符

# 比较操作符
$eq: 等于
$ne: 不等于
$gt: 大于
$gte: 大于等于
$lt: 小于
$lte: 小于等于
$in: 在指定数组中
$nin: 不在指定数组中

# 逻辑操作符
$and: 逻辑与
$or: 逻辑或
$not: 逻辑非
$nor: 既不...也不...

# 示例:多条件查询
db.users.find({
  $and: [
    { age: { $gte: 25 } },
    { age: { $lte: 35 } },
    { $or: [{ name: "Alice" }, { name: "Bob" }] }
  ]
})

五、聚合框架(Aggregation)

聚合框架用于对文档进行复杂的数据处理和统计。

# 统计每个年龄段的用户数量
db.users.aggregate([
  { $group: { _id: "$age", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

# 筛选后计算平均值
db.users.aggregate([
  { $match: { age: { $gte: 25 } } },
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
])

# 展开数组字段(例如 hobbies 数组)
db.users.aggregate([
  { $unwind: "$hobbies" },
  { $group: { _id: "$hobbies", count: { $sum: 1 } } }
])

六、索引管理

# 创建单字段索引(升序)
db.users.createIndex({ name: 1 })

# 创建复合索引
db.users.createIndex({ name: 1, age: -1 })

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

# 查看集合的所有索引
db.users.getIndexes()

# 删除索引
db.users.dropIndex("name_1")  # 索引名通常为 "字段名_顺序"

七、用户与权限管理

# 切换到 admin 数据库
use admin

# 创建管理员用户
db.createUser({
  user: "admin",
  pwd: "password123",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})

# 创建普通用户(只能访问 testdb 数据库)
use testdb
db.createUser({
  user: "testuser",
  pwd: "testpassword",
  roles: [{ role: "readWrite", db: "testdb" }]
})

# 查看用户
show users

# 修改用户密码
db.changeUserPassword("testuser", "newpassword")

# 删除用户
db.dropUser("testuser")

八、备份与恢复

# 导出整个数据库(生成 BSON 文件)
mongodump --db testdb --out /path/to/backup/

# 导入备份数据
mongorestore --db testdb /path/to/backup/testdb/

# 导出集合为 JSON/CSV(适合小数据量)
mongoexport --db testdb --collection users --out users.json
mongoexport --db testdb --collection users --type=csv --fields name,age --out users.csv

# 导入 JSON/CSV 文件
mongoimport --db testdb --collection users --file users.json
mongoimport --db testdb --collection users --type=csv --headerline --file users.csv

九、MongoDB 服务控制(Windows)

# 启动 MongoDB 服务
net start MongoDB

# 停止 MongoDB 服务
net stop MongoDB

# 查看服务状态
sc query MongoDB

十、配置文件修改(mongod.cfg)

# 数据目录
storage:
  dbPath: C:\data\db

# 日志目录
systemLog:
  destination: file
  path: C:\data\log\mongod.log

# 网络配置
net:
  port: 27017
  bindIp: 127.0.0.1  # 仅本地访问,改为 0.0.0.0 允许所有 IP

# 启用身份验证
security:
  authorization: enabled

 

以下是关于 MongoDB 远程连接问题的结构化总结与操作指南,帮助你快速定位和解决连接故障:

十一、核心问题分类与解决方案以及可以让外部连接到你数据库

1. 服务未启动
  • 症状
    • 命令行执行 net start MongoDB 提示服务不存在或无法启动。
    • 连接时提示 connection refused 或超时。
  • 解决步骤
    1. 确认安装路径
      • 确保 MongoDB 已正确安装(参考 Windows 安装指南)。
      • 默认安装路径:C:\Program Files\MongoDB\Server\<版本>\
    2. 手动启动服务

      powershell

      # 以管理员身份打开命令提示符
      net start MongoDB  # 启动服务
      sc query MongoDB   # 检查服务状态(应为 RUNNING)
      

    3. 修复服务配置
      • 若服务未注册,使用以下命令重新安装(需指定数据目录和日志目录):

        powershell

        mongod --config "C:\Program Files\MongoDB\Server\6.0\bin\mongod.cfg" --install --serviceName "MongoDB"
        
2. 绑定地址(bindIp)配置错误
  • 症状
    • 只能通过 localhost 或 127.0.0.1 连接,无法通过局域网 IP(如 192.168.1.9)连接。
    • netstat -ano | findstr :27017 显示 MongoDB 仅监听 127.0.0.1:27017
  • 解决步骤
    1. 编辑配置文件
      • 打开 mongod.cfg(路径:C:\Program Files\MongoDB\Server\<版本>\bin\mongod.cfg)。
      • 修改 net.bindIp 为以下值之一:

        yaml

        net:
          bindIp: 0.0.0.0  # 允许所有 IP 连接(开发环境)
          # 或指定具体局域网 IP(推荐生产环境):
          # bindIp: 192.168.1.9,127.0.0.1
        
    2. 重启服务

      powershell

      net stop MongoDB && net start MongoDB
      
    3. 验证监听地址

      powershell

      netstat -ano | findstr :27017  # 应显示 0.0.0.0:27017 或指定 IP
      
3. 防火墙阻止端口
  • 症状
    • 局域网内其他机器连接时提示 connection timed out 或 10061 拒绝访问
    • telnet 192.168.1.9 27017 无法建立连接。
  • 解决步骤(Windows)
    1. 创建入站规则
      • 打开 控制面板 → Windows 防火墙 → 高级设置
      • 右键 入站规则 → 新建规则 → 选择 端口 → 输入 27017 → 允许连接。
    2. 命令行快速配置(管理员权限)

      powershell

      New-NetFirewallRule -DisplayName "MongoDB 27017" -Direction Inbound -Protocol TCP -LocalPort 27017 -Action Allow
      
    3. 验证端口开放

      powershell

      netsh advfirewall firewall show rule name="MongoDB 27017"  # 确认规则存在
      
4. 网络连通性问题
  • 症状
    • ping 192.168.1.9 超时,无法连通目标机器。
    • 目标机器 IP 配置错误或处于不同子网。
  • 解决步骤
    1. 测试网络连通性

      bash

      # 在客户端执行(Linux/macOS)
      ping 192.168.1.9 -c 4
      
      # 在 Windows 执行
      ping 192.168.1.9
      
    2. 检查 IP 配置
      • 在目标机器执行 ipconfig(Windows)或 ifconfig(Linux)确认 IP 地址正确。
      • 确保客户端与服务器处于同一局域网(如同一路由器下)。
    3. 排查路由或 VPN 问题
      • 若通过 VPN 连接,确认 VPN 已正确配置。
      • 检查目标机器是否启用代理或网络策略限制。
5. 身份验证未启用或凭证错误
  • 症状
    • 配置文件启用了 authorization: enabled,但连接时未提供用户名 / 密码。
    • 提示 Authentication failed 或 Unauthorized
  • 解决步骤
    1. 创建用户并授权

      javascript

      // 在 MongoDB 本地连接中执行
      use admin
      db.createUser({
        user: "remote_user",
        pwd: "strong_password",
        roles: [{ role: "readWriteAnyDatabase", db: "admin" }]
      })
      
    2. 使用带认证的连接字符串

      python

      运行

      # Python 连接示例
      from pymongo import MongoClient
      client = MongoClient(
          "mongodb://remote_user:strong_password@192.168.1.9:27017/?authSource=admin"
      )
      
    3. 临时关闭认证(测试用)
      • 修改 mongod.cfg 移除 security.authorization 配置,重启服务(仅用于调试)。
6. 端口被占用或服务异常
  • 症状
    • 启动 MongoDB 服务时提示端口已被占用(Address already in use)。
    • 其他程序(如另一个 MongoDB 实例)占用了 27017 端口。
  • 解决步骤
    1. 查找占用端口的进程

      powershell

      netstat -ano | findstr :27017  # 记录 PID
      tasklist | findstr <PID>        # 查看进程名称
      
    2. 终止冲突进程或修改端口
      • 终止进程:taskkill /PID <PID> /F
      • 修改 MongoDB 端口(在 mongod.cfg 中添加 port: 27018),重启服务。

连接验证与调试工具

1. 命令行工具验证
  • mongosh 远程连接测试

    bash

    mongosh "mongodb://192.168.1.9:27017/testdb?authSource=admin" -u remote_user -p
    
     
    • 输入密码后,若进入 testdb> 提示符,说明连接成功。
  • telnet 或 nc 测试端口连通性

    bash

    # Windows(需启用 Telnet 功能)
    telnet 192.168.1.9 27017
    
    # Linux/macOS
    nc -zv 192.168.1.9 27017
    
     
    • 若显示 Connected,说明端口可达。
2. Python 代码调试

python

运行

from pymongo import MongoClient
from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError

try:
    # 带超时的连接(10 秒)
    client = MongoClient(
        "mongodb://192.168.1.9:27017",
        serverSelectionTimeoutMS=10000
    )
    # 发送 ping 命令验证连接
    client.admin.command('ping')
    print("连接成功!服务器版本:", client.server_info()['version'])
except ServerSelectionTimeoutError as e:
    print("连接超时:", e)
except ConnectionFailure as e:
    print("连接失败:", e)

生产环境安全最佳实践

  1. 禁止公网直接暴露端口

    • 通过 VPN、SSH 隧道或内网访问 MongoDB,避免公网 IP 直接连接。
    • 使用云服务商的私有网络(如 AWS VPC、阿里云专有网络)。
  2. 最小化 bindIp 范围

    • 避免使用 0.0.0.0,仅绑定必要的 IP(如 192.168.1.9 和 127.0.0.1):

      yaml

      net:
        bindIp: 192.168.1.9,127.0.0.1
      
  3. 启用 TLS/SSL 加密

    • 配置 MongoDB 启用 SSL 认证,防止数据在网络传输中被窃取。
    • 参考官方文档:MongoDB TLS/SSL 配置
  4. 定期审计与监控

    • 使用 mongotopmongostat 监控数据库性能。
    • 启用审计日志记录所有操作:

      yaml

      security:
        auditLog:
          destination: file
          path: C:\data\log\audit.log
      

四、常见错误代码与含义

错误代码 / 信息可能原因
10061 (WinError)防火墙阻止端口或服务未启动
connection refusedMongoDB 服务未运行或端口被占用
Authentication failed用户名 / 密码错误或认证未启用
timed out网络超时或 bindIp 限制
no primary server available副本集配置错误或主节点故障

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智极Hub

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值