MongoDB

关注公众号 jb51net

关闭
首页 > 数据库 > MongoDB > MongoDB查询文档

MongoDB查询文档的各种技巧和最佳实践

作者:Seal^_^

本文系统介绍了MongoDB查询架构、常用查询方法及其差异、复杂查询条件构建、高级查询技巧(如聚合管道、索引优化)、结果处理与分页、性能优化及安全规范,并涵盖全文检索、地理查询和性能诊断等实用技巧,助力高效、安全的数据操作,需要的朋友可以参考下

1. MongoDB查询架构总览

2. 核心查询方法详解

2.1 find()方法 - 多文档查询

基本语法

db.collection.find(
  <query>,           // 查询条件
  <projection>       // 投影(字段控制)
).<cursor_methods>() // 游标方法

典型查询流程

2.2 findOne()方法 - 单文档查询

特点对比

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

3. 查询条件深度解析

3.1 比较操作符大全

实际应用示例

// 范围查询
db.products.find({
  price: { $gt: 100, $lte: 500 },
  stock: { $exists: true }
});

// 数组查询
db.users.find({
  tags: { $in: ["vip", "premium"] },
  age: { $nin: [18, 19, 20] }
});

3.2 逻辑操作符组合

复杂条件构建

// AND/OR/NOT组合
db.orders.find({
  $and: [
    { status: "completed" },
    { $or: [
      { payment: "credit" },
      { amount: { $gt: 1000 } }
    ]},
    { $not: { userType: "trial" } }
  ]
});

4. 高级查询技巧

4.1 聚合管道查询

实际应用

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 }
]);

4.2 索引优化策略

索引使用原则

ESR规则

覆盖查询

// 创建复合索引
db.users.createIndex({ age: 1, status: 1 });

// 覆盖查询示例
db.users.find(
  { age: { $gt: 25 }, status: "active" },
  { _id: 0, age: 1, status: 1 }
).explain("executionStats");

5. 查询结果处理

5.1 游标控制方法

方法描述示例
sort()结果排序.sort({ age: -1 })
limit()限制数量.limit(10)
skip()跳过文档.skip(20)
count()文档计数.count()
pretty()格式化输出.pretty()

5.2 分页查询实现

// 分页函数
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);

6. 生产环境最佳实践

6.1 查询性能优化

6.2 安全查询规范

// 不安全
const query = eval(`({ ${userInput} })`);

// 安全做法
const query = { status: userInputStatus };
// 设置最大返回文档大小
db.runCommand({ setParameter: 1, maxBSONSize: 16777216 });

// 查询时添加硬限制
db.logs.find().limit(1000);

7. 特殊查询场景

7.1 全文检索

// 创建文本索引
db.articles.createIndex({ content: "text" });

// 文本搜索查询
db.articles.find(
  { $text: { $search: "mongodb tutorial" } },
  { score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } });

7.2 地理空间查询

// 创建2dsphere索引
db.places.createIndex({ location: "2dsphere" });

// 附近地点查询
db.places.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [longitude, latitude]
      },
      $maxDistance: 1000 // 1公里内
    }
  }
});

8. 性能监控与诊断

8.1 explain() 分析

// 获取查询执行计划
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
});

8.2 慢查询日志

// 启用慢查询日志
db.setProfilingLevel(1, 50); // 记录>50ms的操作

// 分析慢查询
db.system.profile
  .find({ op: "query", millis: { $gt: 100 } })
  .sort({ ts: -1 })
  .limit(10);

通过本文的全面介绍,您应该已经掌握了MongoDB查询文档的各种技巧和最佳实践。合理设计查询条件、使用适当的索引并遵循性能优化原则,可以显著提升查询效率和应用响应速度。

以上就是MongoDB查询文档的各种技巧和最佳实践的详细内容,更多关于MongoDB查询文档的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文