第5课: 查询操作符
比较操作符
| 操作符 |
说明 |
示例 |
| $eq |
等于 |
{ age: { $eq: 25 } } |
| $ne |
不等于 |
{ age: { $ne: 25 } } |
| $gt |
大于 |
{ age: { $gt: 25 } } |
| $gte |
大于等于 |
{ age: { $gte: 25 } } |
| $lt |
小于 |
{ age: { $lt: 25 } } |
| $lte |
小于等于 |
{ age: { $lte: 25 } } |
| $in |
在数组中 |
{ age: { $in: [20, 25, 30] } } |
| $nin |
不在数组中 |
{ age: { $nin: [20, 25] } } |
// 查询年龄大于25的用户
db.users.find({ age: { $gt: 25 } })
// 查询年龄在20-30之间的用户
db.users.find({ age: { $gte: 20, $lte: 30 } })
// 查询城市为北京或上海的用户
db.users.find({ city: { $in: ["北京", "上海"] } })
逻辑操作符
// $and - 逻辑与(默认)
db.users.find({
$and: [
{ age: { $gte: 18 } },
{ city: "北京" }
]
})
// 简写形式(推荐)
db.users.find({ age: { $gte: 18 }, city: "北京" })
// $or - 逻辑或
db.users.find({
$or: [
{ age: { $lt: 18 } },
{ age: { $gt: 60 } }
]
})
// $nor - 逻辑非或
db.users.find({
$nor: [
{ age: { $lt: 18 } },
{ status: "inactive" }
]
})
// $not - 逻辑非
db.users.find({ age: { $not: { $gte: 18 } } })
元素操作符
// $exists - 字段是否存在
db.users.find({ email: { $exists: true } })
db.users.find({ phone: { $exists: false } })
// $type - 字段类型
db.users.find({ age: { $type: "number" } })
db.users.find({ age: { $type: "string" } })
// 常用类型代码
// "double" (1), "string" (2), "object" (3), "array" (4)
// "bool" (8), "date" (9), "null" (10), "int" (16), "long" (18)
数组操作符
// $all - 数组包含所有指定元素
db.users.find({ hobbies: { $all: ["读书", "旅游"] } })
// $elemMatch - 数组元素匹配条件
db.users.find({
scores: {
$elemMatch: { $gte: 80, $lt: 90 }
}
})
// $size - 数组长度
db.users.find({ hobbies: { $size: 3 } })
正则表达式
// $regex - 正则匹配
db.users.find({ name: { $regex: /^张/ } }) // 姓张
db.users.find({ email: { $regex: /@gmail\.com$/ } }) // Gmail邮箱
// 不区分大小写
db.users.find({ name: { $regex: /zhang/i } })
// 使用字符串形式
db.users.find({ name: { $regex: "^张", $options: "i" } })
文本搜索
// 创建文本索引
db.articles.createIndex({ title: "text", content: "text" })
// 文本搜索
db.articles.find({ $text: { $search: "MongoDB 教程" } })
// 精确短语搜索
db.articles.find({ $text: { $search: "\"NoSQL数据库\"" } })
// 排除词
db.articles.find({ $text: { $search: "MongoDB -SQL" } })
复杂查询示例
// 组合多个条件
db.products.find({
$and: [
{ price: { $gte: 100, $lte: 1000 } },
{ stock: { $gt: 0 } },
{
$or: [
{ category: "电子产品" },
{ tags: { $in: ["热销", "推荐"] } }
]
}
]
})
// 嵌套文档查询
db.users.find({
"address.city": "北京",
"address.district": { $in: ["朝阳区", "海淀区"] }
})
// 数组嵌套对象查询
db.orders.find({
items: {
$elemMatch: {
productId: "prod123",
quantity: { $gte: 2 }
}
}
})
实战案例
// 电商系统:查询符合条件的商品
db.products.find({
$and: [
{ price: { $gte: 50, $lte: 500 } },
{ stock: { $gt: 0 } },
{ rating: { $gte: 4.0 } },
{
$or: [
{ discount: { $exists: true } },
{ tags: "热销" }
]
}
]
}).sort({ sales: -1 }).limit(20)
// 用户系统:查询活跃用户
db.users.find({
status: "active",
lastLoginDate: { $gte: new Date("2026-01-01") },
$or: [
{ vipLevel: { $gte: 2 } },
{ totalOrders: { $gte: 10 } }
]
})
练习题:
- 查询年龄不在18-60之间的用户
- 查询有邮箱但没有手机号的用户
- 查询爱好包含"读书"和"旅游"的用户
- 查询姓名以"李"开头的用户
- 查询价格在100-500之间且库存大于10的商品
- 查询评分数组中至少有一个分数在90-100之间的学生