mongoDB官网 https://docs.mongodb.com/
一、概念
-
名词
- mysql中的表,在mongo中叫collection
- row,对应叫document
- column,对应field
-
文档模型 (Document)
- JSON/BSON格式,便于struct映射
- 方便的文档嵌套,无需Join
- 对document操作是原子的
-
Schema灵活
- 无需预定义
- 每条document的schema可以不一样
(相似schema的document放到一个collection里面) - 支持schema-validation
-
丰富算子(operator)
- 算子也设计为BSON文档模型。
-
聚合功能 (Aggregation)
二、原理
-
Replica set
高可用的实现与一致性的配置。- 包含primary和多个secondary。
- raft协议选主。
- 读参数:readConcern、readPreference
- 写参数:w、j
- 从节点拉取oplog (operation log),进行数据同步
- 主节点宕机,未同步数据将回滚
-
Shard
分片,水平扩展的实现- 根据Shard Key 的不同分片方式
- range分片
- hash分片(单挑查询较多时有利)
- 可以一个或多个字段组合为一个Shard Key,避免Shard Key单调增长。
- 集群根据各shard上chunk数量不均衡情况,自动触发chunk搬迁(split / merge)
- chunk分裂不搬迁数据,只是更改集群的meta数据。
-
WiredTiger引擎
WiredTiger(WT)目前是MongoDB默认的存储引擎。Document Level Concurrency
- 多个client可以同时修改一个collection中的不同document
- WiredTiger采用乐观的并发控制,collection以上层级只使用intent lock
- 遇到冲突会自动重试
Snapshots and Checkpoints
- WiredTiger 使用多版本并发控制(MVCC)。在操作开始时,WiredTiger 为内存中的数据提供快照。
- WiredTiger将快照落盘时,形成checkpoint,checkpoint可以用来恢复数据。
Journal
- checkpoints之间的操作,WT用一个WAL去记录
(持久化通过checkpoints和journal来保证)
Cache
- mongoDB使用了WT和文件系统的cache
- 通过将热数据放入内存cache中,极大的提升查找效率。(b+树)
-
索引
- 单键索引
db.students.createIndex(
{"score":1},
{ unique: true},
{ sparse: true},
{ partialFilterExpression: { score: { $gt: 5 } }
)
- 联合索引 (compound indexes)
db.students.createIndex( {"userid":1, "score":-1} )
db.students.find().sort( { userid: 1, score: -1 } )
db.students.find().sort( { userid: -1, score: 1 } )
-
多值索引(Multikey indexes)
MongoDB 自动为array中的值创建multikey索引,无需显式制定 -
文本索引 (Text indexes)
db.reviews.createIndex( { comments: “text” } ) -
TTL 索引
只能对date values 字段设置
过期后自动清除document
db.eventlog.createIndex(
{ "lastModifiedDate": 1 },
{ expireAfterSeconds: 3600 }
)
- 2d索引
- 地理空间索引
- 通配符索引
- …
三、面试题链接
https://juejin.cn/post/6844904186300071943
https://mp.weixin.qq.com/s/ql5ufi5JinUdIn0MUKKauw
WT原理补充:https://blog.csdn.net/z591045/article/details/112302064