15人参与 • 2025-10-18 • mongodb

基本语法:
db.collection.find( <query>, // 查询条件 <projection> // 投影(字段控制) ).<cursor_methods>() // 游标方法
典型查询流程:

特点对比:
| 特性 | find() | findone() |
|---|---|---|
| 返回结果 | 游标对象 | 文档对象/null |
| 性能 | 需迭代获取结果 | 立即返回单个结果 |
| 适用场景 | 批量数据检索 | 主键或唯一条件查询 |
// 示例:用户登录查询
const user = db.users.findone(
{ username: "alice123" },
{ password: 0 } // 排除密码字段
);

实际应用示例:
// 范围查询
db.products.find({
price: { $gt: 100, $lte: 500 },
stock: { $exists: true }
});
// 数组查询
db.users.find({
tags: { $in: ["vip", "premium"] },
age: { $nin: [18, 19, 20] }
});
复杂条件构建:
// and/or/not组合
db.orders.find({
$and: [
{ status: "completed" },
{ $or: [
{ payment: "credit" },
{ amount: { $gt: 1000 } }
]},
{ $not: { usertype: "trial" } }
]
});

实际应用:
db.sales.aggregate([
{ $match: { date: { $gte: new date("2023-01-01") } } },
{ $project: { product: 1, total: { $multiply: ["$price", "$quantity"] } } },
{ $group: { _id: "$product", totalsales: { $sum: "$total" } } },
{ $sort: { totalsales: -1 } },
{ $limit: 10 }
]);
索引使用原则:
esr规则:
覆盖查询:
// 创建复合索引
db.users.createindex({ age: 1, status: 1 });
// 覆盖查询示例
db.users.find(
{ age: { $gt: 25 }, status: "active" },
{ _id: 0, age: 1, status: 1 }
).explain("executionstats");
| 方法 | 描述 | 示例 |
|---|---|---|
| sort() | 结果排序 | .sort({ age: -1 }) |
| limit() | 限制数量 | .limit(10) |
| skip() | 跳过文档 | .skip(20) |
| count() | 文档计数 | .count() |
| pretty() | 格式化输出 | .pretty() |
// 分页函数
function paginate(collection, query, page = 1, pagesize = 10) {
const skip = (page - 1) * pagesize;
return {
data: collection.find(query).skip(skip).limit(pagesize).toarray(),
total: collection.countdocuments(query),
page,
pagesize
};
}
// 使用示例
const result = paginate(db.products, { category: "electronics" }, 2);

// 不安全
const query = eval(`({ ${userinput} })`);
// 安全做法
const query = { status: userinputstatus };
// 设置最大返回文档大小
db.runcommand({ setparameter: 1, maxbsonsize: 16777216 });
// 查询时添加硬限制
db.logs.find().limit(1000);
// 创建文本索引
db.articles.createindex({ content: "text" });
// 文本搜索查询
db.articles.find(
{ $text: { $search: "mongodb tutorial" } },
{ score: { $meta: "textscore" } }
).sort({ score: { $meta: "textscore" } });
// 创建2dsphere索引
db.places.createindex({ location: "2dsphere" });
// 附近地点查询
db.places.find({
location: {
$near: {
$geometry: {
type: "point",
coordinates: [longitude, latitude]
},
$maxdistance: 1000 // 1公里内
}
}
});
// 获取查询执行计划
const explanation = db.orders
.find({ status: "shipped", amount: { $gt: 100 } })
.explain("executionstats");
// 关键指标解读
console.log({
executiontime: explanation.executionstats.executiontimemillis,
totaldocsexamined: explanation.executionstats.totaldocsexamined,
indexused: explanation.executionstats.executionstages.inputstage.indexname
});
// 启用慢查询日志
db.setprofilinglevel(1, 50); // 记录>50ms的操作
// 分析慢查询
db.system.profile
.find({ op: "query", millis: { $gt: 100 } })
.sort({ ts: -1 })
.limit(10);
通过本文的全面介绍,您应该已经掌握了mongodb查询文档的各种技巧和最佳实践。合理设计查询条件、使用适当的索引并遵循性能优化原则,可以显著提升查询效率和应用响应速度。
以上就是mongodb查询文档的各种技巧和最佳实践的详细内容,更多关于mongodb查询文档的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论