为什么用 MongoDB

关系型表结构固定、要 JOIN;MongoDB 用文档(类似 JSON)存储,结构灵活、天然契合对象、易水平扩展。

核心概念对照

MySQLMongoDB
数据库数据库
表集合 collection
行文档 document
列字段

CRUD

# 插入
db.users.insertOne({ name: "张三", age: 28, tags: ["admin"] })

# 查询
db.users.find({ age: { $gt: 20 } })
db.users.findOne({ name: "张三" })

# 更新
db.users.updateOne({ name: "张三" }, { $set: { age: 30 } })

# 删除
db.users.deleteOne({ name: "张三" })

聚合管道

db.orders.aggregate([
  { $match: { status: "paid" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
])
选型:关系复杂、强一致性用 MySQL;结构多变、高并发读、日志/JSON 数据用 MongoDB。