30分鐘開始
分布式系統理論:
CAP:
一致性
可用性
分區容錯性
MongoDB:
安裝
crud
索引
副本集
分片
NoSQL:非關系型、分布式、不提供ACID功能
技術特點:
1、簡單數據模型
2、元數據和應用數據分離(分不同服務器存儲)
3、弱一致性
優勢:
1、避免不必要的復雜性
2、高吞吐量
3、高水平擴展能力和低端硬件集群
4、不適用對象-關系映射
劣勢:
1、不支持ACID特性
2、功能簡單
3、沒有統一的數據查詢模型
分類:
NoSQL:
鍵值存儲
列式數據庫
文檔數據庫
圖式數據庫
SQL:
mysql
pgsql
緩存數據庫系統:
memcache
CAP理論:從CAP中挑出2個
BASE理論:
基本可用
軟狀態
最終一致性
C,A:SQL(保證一致性,可用性)
C,P:悲觀加鎖機制(一致性,分區容錯性)
A,P:DNS
數據一致性模型:強一致性、弱一致性、最終一致性
數據一致性的實現技術:
Quorum(法定票數)系統NRW策略(關注)
N:副本數
R:完成讀操作所需要讀取的最少副本數
W:完成寫操作所需要寫入的最少副本數
要想保證強一致性:R+W>N
最多只能保證最終一致性:R+W<=N
兩段式提交:2PC(two phase commit protocol)(關注)
有兩類節點:
一類為協調者
一類為事務參與者
兩段:
1、請求階段:事務協調者通知事務參與者提交事務
2、提交階段:事務參與者提交事務
時間戳策略
Paxos:根據協議進行協調
向量時鐘
NoSQL的數據存儲模型:
1、鍵值存儲:k-w
優點:查找迅速
缺點:數據無結構、通常只被當做字符串或二進制數據
應用場景:內容緩存
實例:redis,dynamo
2、列式模型:
數據模型:數據按列存儲,將同一列數據存在一起
優點:查找迅速,可擴展性強,易于實現分布式
缺點:功能相對sql有限
應用場景:分布式文件系統或分布式存儲
實例:Bigtable(google),cassandra,HBase,Hypertable
3、文檔模型
數據模型:與鍵值模型相似,value指向結構化數據
優點:數據格式要求不嚴格,無需事先定義結構
缺點:查詢性能不高,缺乏統一查詢語法
應用場景:web應用
實例:MongoDB,CouchDB
4、圖式模型:
數據模型:圖結構模型
優點:利用圖結構相關算法提高性能,滿足特殊場景應用需求
缺點:實現分布式較困難,功能有定向性
應用場景:社交網絡、推薦系統、關系圖譜
實例:Neo4j
www.nosql-database.org
Mongodb:
collection:表
多個collection:database
MongoDB的安裝:是一個易于擴展的、高性能、開源、文檔模式的no-sql數據庫
存儲:海量數據、文檔數據庫、不需要創建表結構、c++研發的,開源
是什么?
基于文檔數據庫(json格式)
無表結構
性能:
c++
支持各種索引
不支持事務
內存映射(延遲寫操作)
擴展性:
復制
auto-sharding
商業支持
支持基于文檔的查詢:表達式為json
支持使用map/reduce
靈活的聚合操作
在分片的基礎上并行處理
GridFS:網格文件系統,存儲單個大文件或海量小文件的分布式文件系統
地理位置、空間索引
被生產環境驗證過
特性:
動態查詢
查詢性能剖析
基于復制完成故障自動轉移
rabbitmq的性能太差,使用HBase
適應場景:
web網站
緩存
低價值、高存儲量
高擴展性
實現對象、json存儲的應用編程環境
不適合場景:
事務型
商業智能決策
使用sql接口的
MongoDB數據模型:面向集合的數據庫
數據庫:無需創建
表:集合(行):由文檔組成,多個文檔組成一個表,文檔是json格式的(可以嵌套),集合無需事先定義
c/s:
mongod服務器端
mongo
安裝:
查看配置文件:
[root@stu?~]#?cat?/etc/mongod.conf? #?mongo.conf #where?to?log logpath=/var/log/mongo/mongod.log logappend=true #?fork?and?run?in?background fork?=?true #port?=?27017 dbpath=/var/lib/mongo???#運行mongod服務的用戶也是mongod,所以保證這個目錄的屬主屬組也為mongod, 為了數據使用,應該找一個合理的目錄 #?location?of?pidfile pidfilepath?=?/var/run/mongodb/mongod.pid #?Disables?write-ahead?journaling #?nojournal?=?true #?Enables?periodic?logging?of?CPU?utilization?and?I/O?wait #cpu?=?true #?Turn?on/off?security.??Off?is?currently?the?default #noauth?=?true #auth?=?true #?Verbose?logging?output. #verbose?=?true #?Inspect?all?client?data?for?validity?on?receipt?(useful?for #?developing?drivers) #objcheck?=?true #?Enable?db?quota?management #quota?=?true #?Set?oplogging?level?where?n?is #???0=off?(default) #???1=W #???2=R #???3=both #???7=W+some?reads #diaglog?=?0 #?Ignore?query?hints #nohints?=?true #?Disable?the?HTTP?interface?(Defaults?to?localhost:27018). #nohttpinterface?=?true #?Turns?off?server-side?scripting.??This?will?result?in?greatly?limited #?functionality #noscripting?=?true #?Turns?off?table?scans.??Any?query?that?would?do?a?table?scan?fails. #notablescan?=?true #?Disable?data?file?preallocation. #noprealloc?=?true #?Specify?.ns?file?size?for?new?databases. #?nssize?=?<size> #?Accout?token?for?Mongo?monitoring?server. #mms-token?=?<token> #?Server?name?for?Mongo?monitoring?server. #mms-name?=?<server-name> #?Ping?interval?for?Mongo?monitoring?server. #mms-interval?=?<seconds> #?Replication?Options #?in?replicated?mongo?databases,?specify?here?whether?this?is?a?slave?or?master #slave?=?true #source?=?master.example.com #?Slave?only:?specify?a?single?database?to?replicate #only?=?master.example.com #?or #master?=?true #source?=?slave.example.com
創建目錄,改屬主屬組
修改配置文件
啟動服務
system數據庫保存其他數據庫的元數據(和myslq中的mysql數據庫一樣)
查看端口:
27017:服務端口
28017:管理端口
NoSQL數據庫一般是在內網中使用的,不進行認證,直接連
數據庫幫助:
>?db.help function?()?{ ????print("DB?methods:"); ????print("\tdb.addUser(userDocument)"); ????print("\tdb.adminCommand(nameOrDocument)?-?switches?to?'admin'?db,?and?runs?command?[?just?calls?db.runCommand(...)?]"); ????print("\tdb.auth(username,?password)"); ????print("\tdb.cloneDatabase(fromhost)"); ????print("\tdb.commandHelp(name)?returns?the?help?for?the?command"); ????print("\tdb.copyDatabase(fromdb,?todb,?fromhost)"); ????print("\tdb.createCollection(name,?{?size?:?...,?capped?:?...,?max?:?...?}?)"); ????print("\tdb.currentOp()?displays?currently?executing?operations?in?the?db"); ????print("\tdb.dropDatabase()"); ????print("\tdb.eval(func,?args)?run?code?server-side"); ????print("\tdb.fsyncLock()?flush?data?to?disk?and?lock?server?for?backups"); ????print("\tdb.fsyncUnlock()?unlocks?server?following?a?db.fsyncLock()"); ????print("\tdb.getCollection(cname)?same?as?db['cname']?or?db.cname"); ????print("\tdb.getCollectionNames()"); ????print("\tdb.getLastError()?-?just?returns?the?err?msg?string"); ????print("\tdb.getLastErrorObj()?-?return?full?status?object"); ????print("\tdb.getMongo()?get?the?server?connection?object"); ????print("\tdb.getMongo().setSlaveOk()?allow?queries?on?a?replication?slave?server"); ????print("\tdb.getName()"); ????print("\tdb.getPrevError()"); ????print("\tdb.getProfilingLevel()?-?deprecated"); ????print("\tdb.getProfilingStatus()?-?returns?if?profiling?is?on?and?slow?threshold"); ????print("\tdb.getReplicationInfo()"); ????print("\tdb.getSiblingDB(name)?get?the?db?at?the?same?server?as?this?one"); ????print("\tdb.hostInfo()?get?details?about?the?server's?host"); ????print("\tdb.isMaster()?check?replica?primary?status"); ????print("\tdb.killOp(opid)?kills?the?current?operation?in?the?db"); ????print("\tdb.listCommands()?lists?all?the?db?commands"); ????print("\tdb.loadServerScripts()?loads?all?the?scripts?in?db.system.js"); ????print("\tdb.logout()"); ????print("\tdb.printCollectionStats()"); ????print("\tdb.printReplicationInfo()"); ????print("\tdb.printShardingStatus()"); ????print("\tdb.printSlaveReplicationInfo()"); ????print("\tdb.removeUser(username)"); ????print("\tdb.repairDatabase()"); ????print("\tdb.resetError()"); ????print("\tdb.runCommand(cmdObj)?run?a?database?command.??if?cmdObj?is?a?string,?turns?it?into?{?cmdObj?:?1?}"); ????print("\tdb.serverStatus()"); ????print("\tdb.setProfilingLevel(level,<slowms>)?0=off?1=slow?2=all"); ????print("\tdb.setVerboseShell(flag)?display?extra?information?in?shell?output"); ????print("\tdb.shutdownServer()"); ????print("\tdb.stats()"); ????print("\tdb.version()?current?version?of?the?server"); ????return?__magicNoPrint; }
集合幫助:
>?db.mycoll.help() DBCollection?help ????db.mycoll.find().help()?-?show?DBCursor?help ????db.mycoll.count() ????db.mycoll.copyTo(newColl)?-?duplicates?collection?by?copying?all?documents?to?newColl;?no?indexes?are?copied. ????db.mycoll.convertToCapped(maxBytes)?-?calls?{convertToCapped:'mycoll',?size:maxBytes}}?command ????db.mycoll.dataSize() ????db.mycoll.distinct(?key?)?-?e.g.?db.mycoll.distinct(?'x'?) ????db.mycoll.drop()?drop?the?collection ????db.mycoll.dropIndex(index)?-?e.g.?db.mycoll.dropIndex(?"indexName"?)?or?db.mycoll.dropIndex(?{?"indexKey"?:?1?}?) ????db.mycoll.dropIndexes() ????db.mycoll.ensureIndex(keypattern[,options])?-?options?is?an?object?with?these?possible?fields:?name,?unique,?dropDups ????db.mycoll.reIndex() ????db.mycoll.find([query],[fields])?-?query?is?an?optional?query?filter.?fields?is?optional?set?of?fields?to?return. ??????????????????????????????????????????????????e.g.?db.mycoll.find(?{x:77}?,?{name:1,?x:1}?) ????db.mycoll.find(...).count() ????db.mycoll.find(...).limit(n) ????db.mycoll.find(...).skip(n) ????db.mycoll.find(...).sort(...) ????db.mycoll.findOne([query]) ????db.mycoll.findAndModify(?{?update?:?...?,?remove?:?bool?[,?query:?{},?sort:?{},?'new':?false]?}?) ????db.mycoll.getDB()?get?DB?object?associated?with?collection ????db.mycoll.getIndexes() ????db.mycoll.group(?{?key?:?...,?initial:?...,?reduce?:?...[,?cond:?...]?}?) ????db.mycoll.insert(obj) ????db.mycoll.mapReduce(?mapFunction?,?reduceFunction?,?<optional?params>?) ????db.mycoll.remove(query) ????db.mycoll.renameCollection(?newName?,?<dropTarget>?)?renames?the?collection. ????db.mycoll.runCommand(?name?,?<options>?)?runs?a?db?command?with?the?given?name?where?the?first?param?is?the?collection?name ????db.mycoll.save(obj) ????db.mycoll.stats() ????db.mycoll.storageSize()?-?includes?free?space?allocated?to?this?collection ????db.mycoll.totalIndexSize()?-?size?in?bytes?of?all?the?indexes ????db.mycoll.totalSize()?-?storage?allocated?for?all?data?and?indexes ????db.mycoll.update(query,?object[,?upsert_bool,?multi_bool])?-?instead?of?two?flags,?you?can?pass?an?object?with?fields:?upsert,?multi ????db.mycoll.validate(?<full>?)?-?SLOW ????db.mycoll.getShardVersion()?-?only?for?use?with?sharding ????db.mycoll.getShardDistribution()?-?prints?statistics?about?data?distribution?in?the?cluster ????db.mycoll.getSplitKeysForChunks(?<maxChunkSize>?)?-?calculates?split?points?over?all?chunks?and?returns?splitter?function
簡單使用:
使用數據庫:(無需創建),collection也無需創建
db.collection.insert:插入
show collections:查詢集合
db.collections.find():查詢語句
db.collections.update():更新
db.collections.remove():移除
集合信息:
刪除集合:
查看數據庫文件:
基本操作:
show dbs:查看所有數據庫
show collections:查看集合
show users:查看用戶
show profile:
show logs:查看所有日志列表
show log [name]:查看具體的日志
遠程連接:
mongo –host ip
crud操作:
create,read,update,delete
雖然沒有表結構,但還是應該對同類對象放到一個collection
查詢:
db.users.find({age:{$gt:18}}).sort({age:1})?? 查詢age大于18的用戶,以age為升序進行排序
插入:
db.users.insert(
{
name:’suse’,
age:26,
status:’A’,
group:[‘news’,’sports’]
}
)
更新:
db.coll.update(
{age:{$gt:18}},
{$set:{status:’A’}},
{multi:true}?? 不指定時只修改第一個符合條件
)
刪除:
db.coll.delete(
{status:’D’}
)
插入:
一批只顯示20個,輸入it繼續
limit:
刪除:
修改:
find高級用法:
db.collection.find(<添加>,<字段>)
db.collection.count()返回條數
比較運算:
$gt:大于{field:{$gt:value}}
$gte:大于等于{field:{$gte:value}}
$in:存在于{field:{$in:[value1,value2,…]}}
$lt:小于{field:{$lt:value}}
$lte:小于等于{field:{$lte:value}}
$ne:不等于{field:{$ne:value}}
$nin:不存在于{field:{$nin:[value1,value2…]}}
大于
顯示需要的字段:
邏輯運算:
$or:或運算,{$or:[{expression1},{expression2},…]}
$and:或運算,{$and:[{expression1},{expression2},…]}
$not:或運算,{field:{$not:{operator-expression}}}
$nor:反運算,即返回不符合所有指定條件的文檔,{$nor:[{expression1},{expression2},…]}
與運算:
元素查詢:
如果要分居文檔中是否存在某字段等條件來挑選文檔,則需要用到元素運算
$exists:根據指定字段的存在性挑選文檔,語法:{field:{$exists:<boolean>}},指定<boolean>的值為’true’則返回存在指定字段的文檔,’false’則返回不存在指定字段的文檔
$mod:將指定字段的值進行取模運算,并返回其余數作為指定值的文檔,語法{field:{$mod:[divisor,remainder]}}
$type:返回指定字段的值類型為指定類型的文檔,語法:{field:{$type:<bson type>}}
重新插入一條數據:
查詢:
更新:
update專有操作符大致包含:field,array,bitwise
field:
$inc:增大指定字段的值,格式:
db.collection.update({field:value},{$nic:{field1:amount}}),其中{field:value}用于指定挑選標準,{$inc:{field1:amount}}用于指定要提升其值的字段及提升大小amount
$rename:更改字段名,格式為{$rename:{<old name1>:<new name1>,<old name2>:<new name2>,…}}
$set:修改字段的值為新指定的值,格式db.collection.update({field:value1},{$set:{field2:value2}})
$unset:刪除指定的字段,格式db.collection.update({field:value1},{$unset:{field1:””}})
原創文章,作者:黑白子,如若轉載,請注明出處:http://www.www58058.com/60791