一、基本检索1.1 条件查询// ===== 等值 =====db.users.find({ status: "active" })// ===== 比较 =====db.orders.find({
一、基本检索
1.1 条件查询
// ===== 等值 =====
db.users.find({ status: "active" })
// ===== 比较 =====
db.orders.find({ amount: { $gt: 100 } }) // >
db.orders.find({ amount: { $gte: 100 } }) // >=
db.orders.find({ amount: { $lt: 500 } }) // <
db.orders.find({ amount: { $gte: 100, $lte: 500 } }) // 100-500
// ===== in / not in =====
db.products.find({ category: { $in: ["电子", "家居"] } })
db.products.find({ status: { $nin: ["废弃", "下架"] } })
// ===== 不等于 =====
db.users.find({ level: { $ne: "guest" } })
// ===== 存在/不存在 =====
db.users.find({ email: { $exists: true } }) // 有 email 字段
db.users.find({ phone: { $exists: false } }) // 没有 phone 字段
// ===== 类型判断 =====
db.orders.find({ amount: { $type: "double" } }) // 金额为 double 类型
db.orders.find({ amount: { $type: ["int", "long", "double"] } })
1.2 逻辑组合
// and (隐式, 逗号分隔)
db.users.find({ status: "active", age: { $gte: 18 } })
// or
db.users.find({ $or: [
{ status: "active" },
{ viplevel: { $gte: 3 } }
]})
// nor (全部不满足)
db.users.find({ $nor: [
{ status: "banned" },
{ deleted: true }
]})
// not
db.users.find({ age: { $not: { $gte: 18 } } }) // 未满 18
// 组合
db.orders.find({
status: "completed",
$or: [{ channel: "app" }, { channel: "web" }],
amount: { $gt: 100 }
})
1.3 正则与模糊搜索
// 以 "张" 开头
db.users.find({ name: /^张/ })
// 包含 "科技"
db.users.find({ company: /科技/ })
// 不区分大小写
db.products.find({ name: /iphone/i })
// 以 .com 结尾
db.users.find({ email: /\.com$/ })
// $regex 写法
db.users.find({ name: { $regex: "^张", $options: "i" } })
1.4 嵌套文档与数组查询
// ===== 嵌套文档精确匹配 =====
db.orders.find({ "address.city": "北京" })
// ===== 数组包含 =====
db.products.find({ tags: "热销" }) // tags 数组包含 "热销"
db.products.find({ tags: { $all: ["热销", "新品"] } }) // 同时包含
// ===== 数组大小 =====
db.users.find({ hobbies: { $size: 3 } }) // 正好 3 个爱好
// ===== $elemmatch: 数组元素复合条件 =====
db.orders.find({
items: { $elemmatch: { product: "sku001", qty: { $gt: 5 } } }
})
// ===== 数组第 n 个元素 =====
db.orders.find({ "items.0.product": "sku001" }) // 第一个元素
1.5 投影与分页
// 只返回指定字段
db.users.find({}, { name: 1, email: 1, _id: 0 })
// 排除某些字段
db.users.find({}, { password: 0, salt: 0 })
// 分页 (skip + limit)
db.orders.find({}).skip(20).limit(10) // 第 3 页
// 游标分页 (推荐, 利用索引)
db.orders.find({ _id: { $gt: lastid } }).limit(50).sort({ _id: 1 })
// 排序
db.orders.find({}).sort({ createdat: -1 }) // 最新在前
db.orders.find({}).sort({ status: 1, amount: -1 }) // 多字段
二、更新操作
2.1 字段更新
// 设置字段
db.users.updateone(
{ _id: userid },
{ $set: { lastlogin: new date(), status: "active" } }
)
// 批量更新
db.orders.updatemany(
{ status: "expired" },
{ $set: { status: "cancelled", cancelledat: new date() } }
)
// 删除字段
db.users.updateone({ _id: userid }, { $unset: { temptoken: "" } })
// 重命名字段
db.products.updatemany({}, { $rename: { "oldname": "newname" } })
// 字段不存在时设置 (insert 时生效)
db.users.updateone(
{ _id: userid },
{ $setoninsert: { createdat: new date() } },
{ upsert: true }
)
2.2 数值增减
// 原子加减
db.products.updateone({ _id: pid }, { $inc: { stock: -1, sold: 1 } })
db.users.updateone({ _id: uid }, { $inc: { points: 10 } })
// 乘法
db.orders.updatemany({}, { $mul: { amount: 1.13 } }) // 加 13% 税
// 取最大/最小
db.scores.updateone({ _id: uid }, { $max: { highscore: 95 } })
db.sensors.updateone({ _id: sid }, { $min: { mintemp: -5 } })
2.3 数组操作
// 推到数组末尾
db.users.updateone({ _id: uid }, { $push: { tags: "vip" } })
// 推到数组末尾 (去重)
db.users.updateone({ _id: uid }, { $addtoset: { tags: "vip" } })
// 一次加多个
db.users.updateone({ _id: uid }, {
$push: { tags: { $each: ["新客", "首单"], $slice: -20 } } // 只保留最后 20
})
// 从数组移除
db.users.updateone({ _id: uid }, { $pull: { tags: "vip" } })
db.users.updateone({ _id: uid }, { $pull: { tags: { $in: ["过期", "禁用"] } } })
// 移除数组首/尾
db.queue.updateone({ _id: qid }, { $pop: { tasks: -1 } }) // 移除第一个
db.queue.updateone({ _id: qid }, { $pop: { tasks: 1 } }) // 移除最后一个
// 更新数组中匹配的元素
db.orders.updateone(
{ _id: oid, "items.sku": "sku001" },
{ $set: { "items.$.status": "shipped" } }
)
2.4 upsert(存在则更新,不存在则插入)
db.carts.updateone(
{ userid: uid },
{
$setoninsert: { userid: uid, createdat: new date() },
$push: { items: { sku: "sku001", qty: 1 } }
},
{ upsert: true }
)
三、聚合查询
3.1 分组统计
// 按字段分组计数
db.orders.aggregate([
{ $group: { _id: "$status", count: { $sum: 1 } } }
])
// 按多字段分组
db.orders.aggregate([
{ $group: {
_id: { channel: "$channel", status: "$status" },
count: { $sum: 1 },
totalamount: { $sum: "$amount" }
}},
{ $sort: { totalamount: -1 } }
])
// 按时间粒度分组 (天)
db.orders.aggregate([
{ $group: {
_id: { $datetostring: { format: "%y-%m-%d", date: "$createdat" } },
revenue: { $sum: "$amount" },
orders: { $sum: 1 }
}},
{ $sort: { _id: -1 } },
{ $limit: 30 }
])
// 按时间粒度分组 (月)
db.orders.aggregate([
{ $group: {
_id: {
year: { $year: "$createdat" },
month: { $month: "$createdat" }
},
revenue: { $sum: "$amount" }
}},
{ $sort: { "_id.year": 1, "_id.month": 1 } }
])
3.2 聚合运算符
db.sales.aggregate([
{ $match: { date: { $gte: isodate("2026-01-01") } } },
{ $group: {
_id: "$productid",
total: { $sum: "$revenue" }, // 求和
avgprice: { $avg: "$price" }, // 平均
minprice: { $min: "$price" }, // 最小值
maxprice: { $max: "$price" }, // 最大值
cnt: { $sum: 1 }, // 计数
firstsale:{ $first: "$date" }, // 第一个
lastsale: { $last: "$date" }, // 最后一个
products: { $addtoset: "$sku" }, // 去重集合
allprices: { $push: "$price" } // 不去重数组
}}
])
3.3 过滤 → 展开 → 分组流水线
// 典型三步: 过滤 → 展开数组 → 分组统计
db.articles.aggregate([
// 1. 过滤: 最近一年
{ $match: { publishdate: { $gte: isodate("2025-01-01") } } },
// 2. 展开标签
{ $unwind: "$tags" },
// 3. 统计
{ $group: { _id: "$tags", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 20 }
])
3.4 分桶统计
// 手动分桶
db.users.aggregate([
{ $bucket: {
groupby: "$age",
boundaries: [0, 18, 25, 35, 50, 100],
default: "未知",
output: { count: { $sum: 1 }, avgbalance: { $avg: "$balance" } }
}}
])
// 自动分桶
db.users.aggregate([
{ $bucketauto: {
groupby: "$balance",
buckets: 5,
output: { count: { $sum: 1 } }
}}
])
3.5 多维度统计(单次查询)
db.orders.aggregate([
{ $match: { createdat: { $gte: isodate("2026-01-01") } } },
{ $facet: {
// 按状态
bystatus: [
{ $group: { _id: "$status", count: { $sum: 1 } } }
],
// 按渠道
bychannel: [
{ $group: { _id: "$channel", count: { $sum: 1 } } }
],
// top 10 客户
topcustomers: [
{ $group: { _id: "$userid", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
]
}}
])
3.6 连表查询
// 基础连表 (orders → users)
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $lookup: {
from: "users",
localfield: "userid",
foreignfield: "_id",
pipeline: [
{ $project: { name: 1, tier: 1, _id: 0 } }
],
as: "user"
}},
{ $unwind: "$user" }
])
// 多表连查
db.orders.aggregate([
{ $lookup: { from: "users", localfield: "userid", foreignfield: "_id", as: "user" } },
{ $lookup: { from: "products", localfield: "productid", foreignfield: "_id", as: "product" } },
{ $unwind: "$user" },
{ $unwind: "$product" },
{ $project: {
_id: 1, amount: 1,
username: "$user.name",
productname: "$product.name"
}}
])
3.7 去重取值
// 查询某字段有哪些取值
db.orders.distinct("status")
// 带过滤条件的去重
db.orders.distinct("channel", { createdat: { $gte: isodate("2026-01-01") } })
// 聚合方式去重
db.orders.aggregate([
{ $group: { _id: "$channel" } }
])
3.8 结果输出
// 输出为新集合
db.orders.aggregate([
{ $group: { _id: "$productid", total: { $sum: "$amount" } } },
{ $out: "product_summary" } // 完全替换
])
// 合并到已有集合
db.orders.aggregate([
{ $group: { _id: "$userid", daily: { $sum: "$amount" } } },
{ $merge: {
into: "user_stats",
on: "_id",
whenmatched: "merge", // 合并
whennotmatched: "insert" // 新文档插入
}}
])
四、文本搜索
// 创建文本索引
db.articles.createindex({ title: "text", content: "text" })
// 搜索单个词
db.articles.find({ $text: { $search: "mongodb" } })
// 搜索多个词 (or 逻辑)
db.articles.find({ $text: { $search: "mongodb 聚合" } })
// 精确短语 (双引号)
db.articles.find({ $text: { $search: "\"聚合管线\"" } })
// 排除词 (-)
db.articles.find({ $text: { $search: "mongodb -mysql" } })
// 按相关性排序
db.articles.find(
{ $text: { $search: "mongodb" } },
{ score: { $meta: "textscore" } }
).sort({ score: { $meta: "textscore" } })
五、统计分析
// ===== 集合统计 =====
db.orders.countdocuments() // 文档总数
db.orders.countdocuments({ status: "completed" }) // 带条件
db.orders.estimateddocumentcount() // 估算 (基于元数据,快)
// ===== 聚合统计 =====
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: null,
totalrevenue: { $sum: "$amount" },
avgorder: { $avg: "$amount" },
maxorder: { $max: "$amount" },
ordercount: { $sum: 1 }
}}
])
// ===== 按小时/星期分布 =====
db.orders.aggregate([
{ $group: {
_id: { $hour: "$createdat" }, // 小时 (0-23)
// _id: { $dayofweek: "$createdat" }, // 星期 (1=周日)
count: { $sum: 1 }
}},
{ $sort: { _id: 1 } }
])
六、索引管理
// 创建索引
db.orders.createindex({ status: 1 }) // 单字段
db.orders.createindex({ status: 1, createdat: -1 }) // 复合
db.orders.createindex({ userid: 1 }, { unique: true }) // 唯一
db.articles.createindex({ title: "text" }) // 文本
db.locations.createindex({ geo: "2dsphere" }) // 地理
// ttl 索引 (自动过期)
db.sessions.createindex({ createdat: 1 }, { expireafterseconds: 3600 })
// 查看索引
db.orders.getindexes()
// 删除索引
db.orders.dropindex("status_1_createdat_-1")
db.orders.dropindexes() // 删除所有非 _id 索引
// 查看索引使用情况
db.orders.aggregate([{ $indexstats: {} }])
// 强制使用索引
db.orders.find({ status: "completed" }).hint({ status: 1 })
七、管理命令
# ===== 查看 =====
show dbs # 所有数据库
show collections # 当前库所有集合
db.stats() # 库统计
db.orders.stats() # 集合统计
# ===== 复制 =====
db.orders.find().foreach(function(d) { db.orders_bak.insert(d) })
# ===== 删除 =====
db.users.deleteone({ _id: uid })
db.users.deletemany({ status: "banned" })
db.temp.drop() # 删除集合
# ===== explain =====
db.orders.find({ status: "completed" }).explain("executionstats")
# ===== 慢查询 =====
db.setprofilinglevel(1, { slowms: 100 }) # 记录 > 100ms 的查询
db.system.profile.find().sort({ ts: -1 }).limit(5).pretty()
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论