作为NoSQL数据库的代表,MongoDB提供了丰富的查询功能。以下是一些高级查询技巧,帮助您更精准地获取所需数据。
// AND条件
db.collection.find({
$and: [
{ price: { $lt: 100 } },
{ category: "electronics" }
]
})
// OR条件
db.collection.find({
$or: [
{ price: { $lt: 50 } },
{ rating: { $gte: 4 } }
]
})
// 查询嵌套文档
db.users.find({
"address.city": "New York"
})
// 查询数组中的元素
db.products.find({
tags: { $in: ["sale", "featured"] }
})
db.orders.aggregate([
{ $match: { status: "completed" } }, // 筛选阶段
{ $group: {
_id: "$customer_id",
total: { $sum: "$amount" }
}
}, // 分组计算
{ $sort: { total: -1 } }, // 排序
{ $limit: 10 } // 限制结果数量
])
db.sales.aggregate([
{
$lookup: { // 类似SQL的JOIN
from: "products",
localField: "product_id",
foreignField: "_id",
as: "product_details"
}
},
{
$unwind: "$product_details" // 展开数组
},
{
$project: { // 选择字段
date: 1,
quantity: 1,
"product_details.name": 1,
"product_details.price": 1
}
}
])
// 单字段索引
db.customers.createIndex({ email: 1 })
// 复合索引
db.orders.createIndex({ customer_id: 1, order_date: -1 })
// 文本索引
db.articles.createIndex({ content: "text" })
// 查看查询执行计划
db.orders.find({ status: "shipped" }).explain("executionStats")
// 强制使用特定索引
db.orders.find({ customer_id: "12345" }).hint({ customer_id: 1 })
// 创建地理空间索引
db.places.createIndex({ location: "2dsphere" })
// 附近查询
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [ -73.9667, 40.78 ]
},
$maxDistance: 1000 // 1公里范围内
}
}
})
// 创建文本索引
db.articles.createIndex({ title: "text", content: "text" })
// 全文搜索
db.articles.find({
$text: {
$search: "mongodb tutorial -beginner", // 排除beginner
$caseSensitive: false
}
},
{
score: { $meta: "textScore" } // 返回相关性分数
}).sort({ score: { $meta: "textScore" } })
// 更新多个文档
db.products.updateMany(
{ stock: { $lt: 10 } },
{ $set: { status: "low_stock" } }
)
// 向数组添加元素
db.users.update(
{ _id: 123 },
{ $push: { favorites: "mongodb" } }
)
// 从数组删除元素
db.users.update(
{ _id: 123 },
{ $pull: { favorites: "sql" } }
)
// 更新数组中的特定元素
db.products.update(
{ "variants.id": "v1" },
{ $set: { "variants.$.price": 29.99 } }
)
使用投影减少返回数据量:
db.users.find({}, { name: 1, email: 1, _id: 0 })
批量操作减少网络开销:
db.collection.bulkWrite([
{ insertOne: { document: { ... } } },
{ updateOne: { filter: { ... }, update: { ... } } },
{ deleteOne: { filter: { ... } } }
])
使用游标处理大数据集:
const cursor = db.largeCollection.find().batchSize(100)
while (cursor.hasNext()) {
const doc = cursor.next()
// 处理文档
}
监控慢查询:
// 启用慢查询日志
db.setProfilingLevel(1, { slowms: 100 })
// 查看慢查询
db.system.profile.find().sort({ millis: -1 }).limit(10)
通过掌握这些高级查询技巧,您可以更有效地从MongoDB中提取所需数据,优化查询性能,并构建更强大的应用程序。