mongodb是一個(gè)開源的分布式文檔數(shù)據(jù)庫,介于關(guān)系型和非關(guān)系型數(shù)據(jù)庫之間,支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似json和bson格式,支持比較復(fù)雜的數(shù)據(jù)格式,支持復(fù)雜的查詢,支持對(duì)數(shù)據(jù)建立索引。
1、網(wǎng)絡(luò)資源
官網(wǎng):http://www.mongodb.org/
源碼:https://github.com/mongodb/mongo
wiki:https://github.com/mongodb/mongo/wiki
2、組件和工具
bin/mongod - The database process.
bin/mongos - Sharding controller.
bin/mongo? - The database shell (uses interactive javascript).
bsondump-display BSON files in a human-readable format
mongoimport-Convert data from JSON, TSV or CSV and insert them into a collection
mongoexport-Write an existing collection to CSV or JSON format
mongodump/mongorestore-Dump MongoDB backups to disk in .BSON format, or restore them to a live database
mongostat-Monitor live MongoDB servers, replica sets, or sharded clusters
mongofiles-Read, write, delete, or update files in GridFS
mongooplog-Replay oplog entries between MongoDB servers
mongotop-Monitor read/write activity on a mongo server
3、基本概念
1)數(shù)據(jù)庫
一個(gè)mongodb中可以建立多個(gè)數(shù)據(jù)庫。
MongoDB的默認(rèn)數(shù)據(jù)庫為"db",該數(shù)據(jù)庫存儲(chǔ)在data目錄中。
MongoDB的單個(gè)實(shí)例可以容納多個(gè)獨(dú)立的數(shù)據(jù)庫,每一個(gè)都有自己的集合和權(quán)限,不同的數(shù)據(jù)庫也放置在不同的文件中。
2)文檔
文檔是一個(gè)鍵值(key-value)對(duì)(即BSON)。MongoDB 的文檔不需要設(shè)置相同的字段,并且相同的字段不需要相同的數(shù)據(jù)類型,這與關(guān)系型數(shù)據(jù)庫有很大的區(qū)別,也是 MongoDB 非常突出的特點(diǎn)。
3)集合
集合就是 MongoDB 文檔組,類似于 RDBMS (關(guān)系數(shù)據(jù)庫管理系統(tǒng):Relational Database Management System)中的表格。
集合存在于數(shù)據(jù)庫中,集合沒有固定的結(jié)構(gòu),這意味著你在對(duì)集合可以插入不同格式和類型的數(shù)據(jù),但通常情況下我們插入集合的數(shù)據(jù)都會(huì)有一定的關(guān)聯(lián)性。
4、基本框架
參考:http://www.iteye.com/news/24836
5、分片
為何需要水平分片
1) 減少單機(jī)請(qǐng)求數(shù),降低單機(jī)負(fù)載,提高總負(fù)載
2) 減少單機(jī)的存儲(chǔ)空間,提高總存空間。
下圖一目了然:
mongodb sharding 服務(wù)器架構(gòu)
1) mongos 路由進(jìn)程, 應(yīng)用程序接入mongos再查詢到具體分片。
2) config server 路由表服務(wù)。 每一臺(tái)都具有全部chunk的路由信息。
3) shard為數(shù)據(jù)存儲(chǔ)分片。 每一片都可以是復(fù)制集(replica set)。
6、主從機(jī)制
1)選master
通過心跳來同步節(jié)點(diǎn)間信息并觸發(fā)選舉。
MongoDB選舉和復(fù)制協(xié)議基于Raft協(xié)議,正確性得以保證
在Raft基礎(chǔ)上,擴(kuò)展了選舉和復(fù)制協(xié)議,方便使用和運(yùn)維
選舉規(guī)則:
選舉超時(shí)包括一定隨機(jī)性,減少平票的可能性
同一任期(Term),只為一個(gè)候選人投票
一個(gè)任期內(nèi),得到大多數(shù)投票,則成為主結(jié)點(diǎn)
只有當(dāng)候選人的操作日志至少跟投票人一樣新時(shí),才投贊同票
2)主從同步數(shù)據(jù)
(1)intial sync 全量同步
同步集合數(shù)據(jù)(耗時(shí))
拉取oplog并重放
建立索引(耗時(shí))
拉取oplog并重放
(2)replication 增量同步
不斷拉取master上的oplog并重放