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 中絕大多數查詢需求。實際應用中,建議結合索引優化和查詢計劃分析,以提升大數據量下的查詢性能。