🍃 MongoDB Command Quick Reference

📐 工作原理與說明
按分類聚合條目:遍歷條目列表,首次出現的分類記入有序陣列並把計數置 1,後續同分類累加;柱狀圖以分類名為橫軸、條目數為資料(圖高 300),明細表逐行輸出序號、分類名、該分類條目數與該分類前 2 條代表命令(以「 / 」連線)。分類名在英文態下按內建對映表替換為英文(MongoDB 命令)
MongoDB 常用操作速查。
  • 庫與集合:show dbs、use、db.createCollection、show collections、drop。
  • CRUD:insertOne/insertMany、find、updateOne/updateMany、deleteOne/deleteMany。
  • 查詢:條件運算子 $gt、$in、$regex,投影指定返回欄位,sort/limit/skip 分頁。
  • 聚合:aggregate 管道配合 $match、$group、$sort、$project、$lookup。

Browse a MongoDB cheat sheet in your browser — common queries and aggregation snippets.

📚 深度解析:MongoDB 命令速查

💡 常見使用場景

  • 查閱 find/aggregate/update。
  • 寫聚合管道時查運算元:確認 $match、$group、$lookup 的順序與寫法,尤其注意 $match 應儘量前置以利用索引。
查聚合
`db.orders.aggregate([{$match:{status:"A"}},{$group:{_id:"$cust",total:{$sum:"$amt"}}}])`。

❓ 常見問題(FAQ)

MongoDB 有事務嗎?
4.0+ 支援多文件事務。
為什麼查詢很慢?
先看有沒有走索引:用 explain() 看執行計劃,COLLSCAN 表示全表掃描。常見原因包括查詢欄位沒有索引、用了無法走索引的正則或 $where、排序欄位與索引不匹配。另外 $lookup 相當於 join,資料量大時開銷很高,應考慮冗餘設計或分批處理。

Formula & Standard References

Item Formula / Note Source / Standard
Document model BSON documents with nesting instead of joins MongoDB manual
Index types single-field, compound, multikey, text and geospatial MongoDB manual
Aggregation $match, $group, $sort and $project stage pipeline MongoDB manual
⚠️ 使用說明與注意事項