跳到主要内容

MongoDB 知识速查表

本页面汇总了 MongoDB 最常用的命令和语法,方便快速查阅。

连接与基本操作

// 连接本地 MongoDB
mongosh

// 连接远程 MongoDB
mongosh "mongodb://hostname:27017"

// 带认证连接
mongosh "mongodb://user:password@hostname:27017/database"

// 带副本集连接
mongosh "mongodb://host1:27017,host2:27017/?replicaSet=rs0"

数据库操作

// 查看所有数据库
show dbs

// 切换数据库
use mydb

// 查看当前数据库
db

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

// 查看所有集合
show collections

CRUD 操作

插入文档

// 插入单个文档
db.collection.insertOne({ name: "张三", age: 25 })

// 插入多个文档
db.collection.insertMany([
{ name: "李四", age: 30 },
{ name: "王五", age: 28 }
])

查询文档

// 查询所有文档
db.collection.find()

// 条件查询
db.collection.find({ age: 25 })

// 精确匹配
db.collection.find({ "address.city": "Beijing" })

// 比较运算符
db.collection.find({ age: { $gt: 25 } })
db.collection.find({ age: { $gte: 25, $lte: 30 } })
db.collection.find({ status: { $in: ["active", "pending"] } })

// 逻辑运算符
db.collection.find({ $and: [{ age: { $gt: 20 } }, { status: "active" }] })
db.collection.find({ $or: [{ status: "a" }, { status: "b" }] })

// 数组查询
db.collection.find({ tags: { $all: ["a", "b"] } })
db.collection.find({ scores: { $elemMatch: { $gt: 90 } } })

// 正则表达式
db.collection.find({ name: { $regex: "^张", $options: "i" } })

// 投影
db.collection.find({}, { name: 1, _id: 0 })

// 排序
db.collection.find().sort({ age: 1, name: -1 })

// 分页
db.collection.find().skip(10).limit(20)

// 计数
db.collection.countDocuments({ age: { $gt: 20 } })

更新文档

// 更新单个文档
db.collection.updateOne(
{ name: "张三" },
{ $set: { age: 26 } }
)

// 更新多个文档
db.collection.updateMany(
{ status: "pending" },
{ $set: { status: "processing" } }
)

// 替换文档
db.collection.replaceOne(
{ _id: 1 },
{ name: "新名称", age: 30 }
)

// 原子操作
db.collection.updateOne({}, { $inc: { count: 1 } })
db.collection.updateOne({}, { $push: { tags: "new" } })
db.collection.updateOne({}, { $pull: { tags: "old" } })

// upsert
db.collection.updateOne(
{ name: "test" },
{ $set: { age: 25 } },
{ upsert: true }
)

删除文档

// 删除单个文档
db.collection.deleteOne({ name: "张三" })

// 删除多个文档
db.collection.deleteMany({ status: "deleted" })

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

// 删除字段
db.collection.updateMany({}, { $unset: { tempField: "" } })

聚合管道

// 常用阶段
db.collection.aggregate([
{ $match: { status: "active" } }, // 过滤
{ $group: { _id: "$category", count: { $sum: 1 } } }, // 分组
{ $project: { name: 1, total: 1 } }, // 投影
{ $sort: { count: -1 } }, // 排序
{ $limit: 10 }, // 限制
{ $skip: 20 }, // 跳过
{ $unwind: "$items" }, // 展开数组
{ $lookup: { from: "other", localField: "id", foreignField: "ref", as: "data" } } // 连接
])

// 聚合表达式
{ $sum: "$amount" } // 求和
{ $avg: "$score" } // 平均值
{ $min: "$price" } // 最小值
{ $max: "$price" } // 最大值
{ $first: "$date" } // 第一个值
{ $last: "$date" } // 最后一个值
{ $concat: ["$firstName", " ", "$lastName"] } // 字符串连接
{ $year: "$createdAt" } // 提取年份

索引操作

// 创建索引
db.collection.createIndex({ name: 1 }) // 单字段索引
db.collection.createIndex({ name: 1, age: -1 }) // 复合索引
db.collection.createIndex({ name: "text" }) // 文本索引
db.collection.createIndex({ location: "2dsphere" }) // 地理空间索引
db.collection.createIndex({ name: 1 }, { unique: true }) // 唯一索引

// 查看索引
db.collection.getIndexes()

// 删除索引
db.collection.dropIndex("name_1")
db.collection.dropIndexes() // 删除所有(除了 _id)

用户与权限

// 创建用户
db.createUser({
user: "username",
pwd: "password",
roles: [{ role: "readWrite", db: "mydb" }]
})

// 查看用户
db.getUsers()

// 删除用户
db.dropUser("username")

// 认证
db.auth("username", "password")

// 创建角色
db.createRole({
role: "customRole",
privileges: [{ resource: { db: "mydb", collection: "" }, actions: ["find", "update"] }],
roles: []
})

副本集操作

// 初始化副本集
rs.initiate({ _id: "rs0", members: [{ host: "localhost:27017" }] })

// 查看状态
rs.status()

// 查看配置
rs.conf()

// 添加成员
rs.add("localhost:27018")

// 移除成员
rs.remove("localhost:27018")

// 手动故障转移
rs.stepDown()

分片操作

// 启用数据库分片
sh.enableSharding("mydb")

// 分片集合
sh.shardCollection("mydb.collection", { shardKey: 1 })

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

// 添加分片
sh.addShard("localhost:27020")

// 均衡器控制
sh.stopBalancer()
sh.startBalancer()

常用查询模式

// 分页查询
db.posts.find()
.sort({ createdAt: -1 })
.skip((page - 1) * pageSize)
.limit(pageSize)

// 模糊搜索
db.products.find({
name: { $regex: keyword, $options: "i" }
})

// 统计每日数据
db.orders.aggregate([
{ $group: {
_id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
count: { $sum: 1 },
total: { $sum: "$amount" }
}},
{ $sort: { _id: 1 } }
])

// 联表查询
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userInfo"
}},
{ $unwind: "$userInfo" },
{ $project: { orderId: 1, userName: "$userInfo.name" } }
])

配置与系统

// 查看服务器状态
db.serverStatus()

// 查看数据库状态
db.stats()

// 查看集合状态
db.collection.stats()

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

// 查看慢查询
db.getProfilingLevel()
db.setProfilingLevel(1, 100) // 记录超过 100ms 的查询

// 分析查询
db.collection.find({}).explain("executionStats")

BSON 数据类型

类型示例
Double3.14
String"hello"
Object{ a: 1 }
Array[1, 2, 3]
ObjectIdObjectId("...")
Booleantrue
Datenew Date()
Nullnull
NumberIntNumberInt(123)
NumberLongNumberLong("...")

常用工具命令

# 导出数据
mongodump --host localhost --db mydb --out /backup

# 导入数据
mongorestore --host localhost --db mydb /backup/mydb

# 导出 JSON
mongoexport --host localhost --db mydb --collection users --out users.json

# 导入 JSON
mongoimport --host localhost --db mydb --collection users --file users.json

# 监控状态
mongostat --host localhost 2

# 查看连接
mongotop --host localhost