MongoDB 命令速查

🍃 MongoDB Command Quick Reference

📐 工作原理與說明
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,資料量大時開銷很高,應考慮冗餘設計或分批處理。
⚠️ 使用說明與注意事項
已複製
📖關於「MongoDB 命令速查」 ▼

📝工具簡介

MongoDB 命令速查。專為開發者打造的線上工具,純前端執行,程式碼不離開瀏覽器。