04 特色及优势 维度 能力 数据模型 多形性(同集合不同字段)、动态性(在线改模式)、JSONSchema 治理 开发体验 单存储区读写、反范式 + 无关联优化、API 自然 高可用 Replica Set(2~50 节点,建议奇数)、自恢复、多中心容灾、滚动维护 横向扩展 无缝扩容、应用透明、多种数据分布策略,可达 TB-PB 06 基本操作 环境与样本数据:
cloud.mongodb.com 云服务 样本数据 dump.tar.gz tar -xvf dump.tar.gz mongorestore --uri="mongodb://root:root@10.130.0.12/?&authMechanism=SCRAM-SHA-1" CRUD // 插入 db.fruit.insertOne({ name: "apple" }) db.fruit.insertMany([{ name: "apple" }, { name: "pear" }, { name: "orange" }]) // 查询 db.customers.find({ username: "fmiller", name: "Elizabeth Ray" }) db.customers.find({ username: /^f/ }) db.customers.find({ $or: [{ username: /^f/ }, { name: /^E/ }] }) // 投影(projection) db.customers.find({ username: /^f/ }, { name: 0, email: 0 }) // 排除 db.customers.find({ username: /^f/ }, { _id: 1, name: 1 }) // 仅返回 // 删除 db.customers.remove({ username: "abrown" }) // 更新 db.customers.updateOne({ username: "fmiller" }, { $set: { from: "China" } }) db.customers.updateMany({ username: "fmiller" }, { $set: { from: "China" } }) // 表 / 库管理 db.fruit.drop() show collections db.dropDatabase() show dbs SQL ↔ Mongo 操作符对照 SQL Mongo a <> 1 {a: {$ne: 1}} a > 1 / >= {a: {$gt: 1}} / {$gte: 1} a < 1 / <= {a: {$lt: 1}} / {$lte: 1} a = 1 OR b = 1 {$or: [{a: 1}, {b: 1}]} a IS NULL {a: {$exists: false}} a IN (1, 2, 3) {a: {$in: [1, 2, 3]}} 同时满足子文档条件 {$elemMatch: {city: "Rome", country: "USA"}} 常用更新操作符 操作 含义 $set / $unset 设置 / 移除字段 $push / $pop 数组追加 / 弹出 $pull / $pullAll 按匹配从数组中删除 $addToSet 不存在则添加,去重 08 聚合查询 Aggregation Framework:
...