MongoDB 常见查询语法与命令详解

发布于:2025-07-04 ⋅ 阅读:(22) ⋅ 点赞:(0)

MongoDB 作为文档型数据库,其查询语言基于 BSON(二进制 JSON)格式,与传统关系型数据库的 SQL 语法有较大差异。

一、基本查询命令

1. find():查询文档

  • 语法db.collection.find(查询条件, 投影)
  • 示例
    // 查询users集合中所有文档
    db.users.find()
    
    // 查询年龄大于25岁的用户,只返回姓名和年龄
    db.users.find({ age: { $gt: 25 } }, { name: 1, age: 1 })
    

2. findOne():查询单个文档

  • 语法db.collection.findOne(查询条件, 投影)
  • 示例
    // 查询ID为1001的用户
    db.users.findOne({ id: 1001 })
    

3. countDocuments():统计文档数量

  • 语法db.collection.countDocuments(查询条件)
  • 示例
    // 统计年龄大于30岁的用户数量
    db.users.countDocuments({ age: { $gt: 30 } })
    

二、查询条件操作符

1. 比较操作符

操作符 含义 示例
$eq 等于 { age: { $eq: 30 } }
$gt 大于 { age: { $gt: 30 } }
$lt 小于 { age: { $lt: 30 } }
$gte 大于等于 { age: { $gte: 30 } }
$lte 小于等于 { age: { $lte: 30 } }
$ne 不等于 { age: { $ne: 30 } }
$in 包含于数组 { age: { $in: [25, 30, 35] } }
$nin 不包含于数组 { age: { $nin: [25, 30, 35] } }

2. 逻辑操作符

  • $and:多条件同时满足
    db.users.find({ $and: [{ age: { $gt: 25 } }, { gender: "male" }] })
    
  • $or:多条件满足其一
    db.users.find({ $or: [{ age: { $gt: 40 } }, { profession: "engineer" }] })
    
  • $not:取反条件
    db.users.find({ age: { $not: { $gt: 30 } } })  // 年龄≤30
    

3. 文本与正则操作符

  • $regex:正则匹配
    db.users.find({ name: { $regex: "^John" } })  // 姓名以John开头
    
  • $text:全文搜索(需先创建文本索引)
    db.users.find({ $text: { $search: "John" } })
    

三、查询结果处理

1. 排序:sort()

  • 语法db.collection.find().sort({ 字段: 1/-1 })
  • 示例
    // 按年龄升序排列
    db.users.find().sort({ age: 1 })
    
    // 按年龄降序、姓名升序排列
    db.users.find().sort({ age: -1, name: 1 })
    

2. 限制结果:limit()

  • 语法db.collection.find().limit(数量)
  • 示例
    // 只返回前10条记录
    db.users.find().limit(10)
    

3. 跳过结果:skip()

  • 语法db.collection.find().skip(数量)
  • 示例
    // 跳过前5条,返回接下来的10条(分页查询)
    db.users.find().skip(5).limit(10)
    

四、聚合查询:aggregate()

聚合操作通过管道(Pipeline)处理文档,常用阶段包括:

1. $match:过滤文档

db.sales.aggregate([
  { $match: { amount: { $gt: 1000 } } }  // 筛选金额>1000的记录
])

2. $group:分组统计

db.sales.aggregate([
  { $group: {
    _id: "$category",  // 按类别分组
    totalAmount: { $sum: "$amount" },  // 计算每组总金额
    count: { $sum: 1 }  // 计算每组文档数
  }}
])

3. $project:投影字段

db.sales.aggregate([
  { $project: {
    category: 1,
    amount: 1,
    isBigOrder: { $gt: ["$amount", 5000] }  // 新增字段标识大额订单
  }}
])

4. $sort/$limit/$skip:同查询结果处理

db.sales.aggregate([
  { $sort: { amount: -1 } },  // 按金额降序
  { $limit: 10 }  // 取前10条
])

五、索引管理命令

1. 创建索引

  • 单字段索引
    db.users.createIndex({ age: 1 })  // 升序索引
    db.users.createIndex({ name: -1 })  // 降序索引
    
  • 复合索引
    db.sales.createIndex({ category: 1, amount: -1 })
    
  • 唯一索引
    db.users.createIndex({ email: 1 }, { unique: true })
    

2. 查看索引

db.users.getIndexes()

3. 删除索引

db.users.dropIndex("age_1")  // 删除指定索引
db.users.dropIndexes()  // 删除所有索引

六、高级查询技巧

1. 数组查询

  • 匹配数组中的元素:
    db.users.find({ hobbies: "reading" })  // 包含reading的用户
    
  • 匹配数组中满足条件的元素:
    db.users.find({ "scores.math": { $gt: 80 } })  // 数学成绩>80
    
  • 数组大小匹配:
    db.users.find({ hobbies: { $size: 3 } })  // 恰好有3个爱好
    

2. 嵌套文档查询

db.users.find({ "address.city": "Beijing" })  // 地址在北京市的用户

七、查询优化命令

1. 解释查询计划

db.users.find({ age: { $gt: 30 } }).explain("executionStats")

2. 统计索引使用情况

db.users.totalIndexSize()  // 查看索引总大小
db.runCommand({ indexStats: "users" })  // 查看详细索引统计

八、SQL 与 MongoDB 查询语法对比

SQL 语法 MongoDB 语法
SELECT * FROM users db.users.find()
SELECT * FROM users WHERE age > 25 db.users.find({ age: { $gt: 25 } })
SELECT * FROM users ORDER BY age DESC LIMIT 10 db.users.find().sort({ age: -1 }).limit(10)
SELECT category, SUM(amount) FROM sales GROUP BY category db.sales.aggregate([{ $group: { _id: "$category", total: { $sum: "$amount" } }]

通过以上常用查询命令,可满足 MongoDB 中绝大多数查询需求。实际应用中,建议结合索引优化和查询计划分析,以提升大数据量下的查询性能。


网站公告

今日签到

点亮在社区的每一天
去签到