插件窝 干货文章 MongoDB高级查询技巧,精准获取所需数据

MongoDB高级查询技巧,精准获取所需数据

javascript 查询 数组 索引 1016    来源:    2025-03-27

MongoDB高级查询技巧:精准获取所需数据

作为NoSQL数据库的代表,MongoDB提供了丰富的查询功能。以下是一些高级查询技巧,帮助您更精准地获取所需数据。

1. 复杂条件查询

1.1 多条件组合查询

// AND条件
db.collection.find({
  $and: [
    { price: { $lt: 100 } },
    { category: "electronics" }
  ]
})

// OR条件
db.collection.find({
  $or: [
    { price: { $lt: 50 } },
    { rating: { $gte: 4 } }
  ]
})

1.2 嵌套查询

// 查询嵌套文档
db.users.find({
  "address.city": "New York"
})

// 查询数组中的元素
db.products.find({
  tags: { $in: ["sale", "featured"] }
})

2. 聚合框架(Aggregation Pipeline)

2.1 基本聚合操作

db.orders.aggregate([
  { $match: { status: "completed" } },  // 筛选阶段
  { $group: { 
      _id: "$customer_id", 
      total: { $sum: "$amount" } 
    } 
  },  // 分组计算
  { $sort: { total: -1 } },  // 排序
  { $limit: 10 }  // 限制结果数量
])

2.2 高级聚合操作

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

3. 索引优化查询

3.1 创建索引

// 单字段索引
db.customers.createIndex({ email: 1 })

// 复合索引
db.orders.createIndex({ customer_id: 1, order_date: -1 })

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

3.2 查询分析

// 查看查询执行计划
db.orders.find({ status: "shipped" }).explain("executionStats")

// 强制使用特定索引
db.orders.find({ customer_id: "12345" }).hint({ customer_id: 1 })

4. 地理空间查询

// 创建地理空间索引
db.places.createIndex({ location: "2dsphere" })

// 附近查询
db.places.find({
  location: {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [ -73.9667, 40.78 ]
      },
      $maxDistance: 1000  // 1公里范围内
    }
  }
})

5. 全文搜索

// 创建文本索引
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" } })

6. 高级更新操作

6.1 批量更新

// 更新多个文档
db.products.updateMany(
  { stock: { $lt: 10 } },
  { $set: { status: "low_stock" } }
)

6.2 数组操作

// 向数组添加元素
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 } }
)

7. 性能优化技巧

  1. 使用投影减少返回数据量

    db.users.find({}, { name: 1, email: 1, _id: 0 })
    
  2. 批量操作减少网络开销

    db.collection.bulkWrite([
     { insertOne: { document: { ... } } },
     { updateOne: { filter: { ... }, update: { ... } } },
     { deleteOne: { filter: { ... } } }
    ])
    
  3. 使用游标处理大数据集

    const cursor = db.largeCollection.find().batchSize(100)
    while (cursor.hasNext()) {
     const doc = cursor.next()
     // 处理文档
    }
    
  4. 监控慢查询

    // 启用慢查询日志
    db.setProfilingLevel(1, { slowms: 100 })
    
    // 查看慢查询
    db.system.profile.find().sort({ millis: -1 }).limit(10)
    

通过掌握这些高级查询技巧,您可以更有效地从MongoDB中提取所需数据,优化查询性能,并构建更强大的应用程序。