🍃 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
⚠️ 使用说明与注意事项