find 的条件不止等值 —— 查询操作符覆盖比较、逻辑、正则、类型判断。本文是查询符速查手册,结尾附商品筛选小案例。
一、比较操作符
db.users.find({ age: { $gt: 18 } }) // 大于
db.users.find({ age: { $gte: 18, $lte: 30 } }) // 18~30 区间
db.users.find({ name: { $ne: "Tom" } }) // 不等于
db.users.find({ tag: { $in: ["vip", "new"] } }) // 在列表中
db.users.find({ tag: { $nin: ["banned"] } }) // 不在列表中
| 操作符 | 含义 |
|---|---|
| $eq / $ne | 等于 / 不等于 |
| $gt / $gte | 大于 / 大于等于 |
| $lt / $lte | 小于 / 小于等于 |
| $in / $nin | 在 / 不在数组列表中 |
二、逻辑操作符
db.users.find({ $and: [{ age: { $gt: 18 } }, { vip: true }] }) // 与
db.users.find({ $or: [{ city: "sz" }, { city: "gz" }] }) // 或
db.users.find({ age: { $not: { $gt: 18 } } }) // 非
db.users.find({ $nor: [{ vip: true }, { age: { $gt: 60 } }] }) // 都不满足
多条件逗号分隔默认 $and;$or 内条件应各有索引(见索引篇)。
三、正则查询
db.users.find({ name: /tom/i }) // 忽略大小写
db.users.find({ name: { $regex: "^To" } }) // 前缀匹配
db.users.find({ email: { $regex: "@example\.com$" } })
db.users.find({ name: { $regex: "tom", $options: "i" } }) // 等价 /tom/i
前缀正则(^开头)能用索引;中缀/后缀会全表扫 —— 全文搜索用 text 索引(索引进阶篇)。
四、元素与类型查询
db.users.find({ addr: { $exists: true } }) // 字段存在
db.users.find({ age: { $type: "int" } }) // 类型为 int
db.users.find({ age: { $mod: [10, 0] } }) // 10 的倍数
五、数组查询语义(重点)
db.users.find({ tags: "vip" }) // tags 含 "vip"(元素匹配)
db.users.find({ tags: { $all: ["vip", "new"] } }) // 同时含两个
db.users.find({ tags: { $size: 2 } }) // 数组长度为 2
db.users.find({ "tags.0": "vip" }) // 第一个元素是 vip
db.users.find({ scores: { $elemMatch: { $gt: 80, $lt: 90 } } }) // 元素满足组合条件
六、注意
- 点号访问嵌套字段:"addr.city";数组里的文档也能这样查;
- 查 null 会同时命中"值为 null"和"字段不存在"(要区分用 $type/$exists);
- $or 整体只有在每个条件都有索引时才高效;
- 类型不敏感查询:"20" 不等于 20。
七、小案例:商品筛选接口
// 电商列表页常见筛选条件组合
db.products.find({
$and: [
{ price: { $gte: 100, $lte: 500 } }, // 价格区间
{ tags: { $in: ["hot", "new"] } }, // 任一标签
{ stock: { $gt: 0 } }, // 有库存
{ deleted: { $exists: false } }, // 未删除
{ $or: [
{ name: { $regex: "键盘" } }, // 名称模糊
{ brand: { $in: ["Logitech", "Razer"] } } // 品牌
]}
]
}).sort({ sales: -1 }).limit(20)
// 促销商品:评分 4.5+ 且至少两个标签
db.products.find({
rate: { $gte: 4.5 },
tags: { $size: 2 }
})
一个 find 融合区间、$in、$exists、$or 模糊、$size —— 真实筛选接口的条件基本就这些。
八、总结
比较 $gt/$in/$ne、逻辑 $and/$or/$not、正则 $regex(前缀可用索引)、元素 $exists/$type/$size;数组查询 "tags" 含元素、$all 全含、$elemMatch 组合;null 语义要小心。