NoSQL理論基礎及安裝、基本操作

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

 

 

安裝:

圖片.png

查看配置文件:

[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
創建目錄,改屬主屬組

圖片.png

修改配置文件

圖片.png

圖片.png

啟動服務

圖片.png

system數據庫保存其他數據庫的元數據(和myslq中的mysql數據庫一樣)

查看端口:

圖片.png

27017:服務端口

28017:管理端口

mongodb_admin.png

NoSQL數據庫一般是在內網中使用的,不進行認證,直接連

圖片.png

圖片.png

數據庫幫助:

>?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

簡單使用:

圖片.png

圖片.png

使用數據庫:(無需創建),collection也無需創建

圖片.png

db.collection.insert:插入

show collections:查詢集合

db.collections.find():查詢語句

db.collections.update():更新

db.collections.remove():移除

集合信息:

圖片.png

刪除集合:

圖片.png

查看數據庫文件:

圖片.png

基本操作:

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’}

)

插入:

圖片.png

圖片.png

一批只顯示20個,輸入it繼續

limit:

圖片.png

刪除:

圖片.png

 

修改:圖片.png

find高級用法:

db.collection.find(<添加>,<字段>)

db.collection.count()返回條數

圖片.png

比較運算:

$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…]}}

大于

圖片.png

顯示需要的字段:

圖片.png

邏輯運算:

$or:或運算,{$or:[{expression1},{expression2},…]}

$and:或運算,{$and:[{expression1},{expression2},…]}

$not:或運算,{field:{$not:{operator-expression}}}

$nor:反運算,即返回不符合所有指定條件的文檔,{$nor:[{expression1},{expression2},…]}

與運算:

圖片.png

元素查詢:

如果要分居文檔中是否存在某字段等條件來挑選文檔,則需要用到元素運算

$exists:根據指定字段的存在性挑選文檔,語法:{field:{$exists:<boolean>}},指定<boolean>的值為’true’則返回存在指定字段的文檔,’false’則返回不存在指定字段的文檔

$mod:將指定字段的值進行取模運算,并返回其余數作為指定值的文檔,語法{field:{$mod:[divisor,remainder]}}

$type:返回指定字段的值類型為指定類型的文檔,語法:{field:{$type:<bson type>}}

重新插入一條數據:

圖片.png

查詢:

圖片.png

更新:

圖片.png

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:””}})

圖片.png

 

 

 

 

 

 

 

 

原創文章,作者:黑白子,如若轉載,請注明出處:http://www.www58058.com/60791

(1)
黑白子黑白子
上一篇 2016-11-27
下一篇 2016-11-27

相關推薦

  • Redis基于Sentinel哨兵高可用方案

    下載最新redis版本,當前最新版本為  2.8.19  2014-12-30 安裝redis 首頁地址:http://redis.io/ 最新穩定版下載地址: http://download.redis.io/releases/redis-2.8.19.tar.gz # tar -xvf redis-2.8.19.tar.gz # cd…

    2015-03-03
  • Linux上文件管理命令、元素據及時間戳、bash的工作特性回顯和命令展開、定義別名,命令引用。

    文件管理命令: mkdir 創建空目錄 語法: mkdir [選項]…目錄… 選項: -P:逐層創建目錄。 -v:顯示過程。 -m:直接給定權限。 注意:路徑的基名為命令作用對象。基名路徑必須存在。 示例 創建/tmp/x1/a/a1和/tmp/x1/b rmdir 移除空目錄 語法 rmdir [選項]…目錄&#8230…

    Linux干貨 2017-12-10
  • Centos系統啟動概括流程

    §·Centos系統啟動概括流程 系統啟動流程: PC (OS Llinux) POST(開機)–>BIOS–>MBR(bootloader .446字節)—>kernel–>/sbin/init(/etc/inittab)(用戶空間的管理進程)   備注: POST :加電自…

    Linux干貨 2016-09-08
  • 作業權限管理

    一、在/data/testdir里創建的新文件自動屬于g1組,組g2的成員如:alice能對這些新文件有讀寫權限,組g3的成員如:tom只能對新文件有讀權限,其它用戶(不屬于g1,g2,g3)不能訪問這個文件夾。 首先創建三個組g1,g2,g3,題目要求在/data/testdir目錄里創建的文件自動屬于g1組那么首先要將這個目錄的屬組改為g1,然后通過更改…

    Linux干貨 2016-08-03
  • Linux的發行版及哲學思想

    Linux是一套免費使用和自由傳播的類Unix系統,是一個基于Unix的多用戶、多任務、支持多線程和多CPU的操作系統。它能運行主要的工具軟件、應用程序和網絡協議。它支持32位和64位硬件,是一個性能穩定的多用戶網絡操作系統。嚴格來講,Linux這個詞本身只表示Linux內核,聯合GNU 組織里的各種強大的應用軟件而組成的操作系統。 從Linux的誕生至今,…

    Linux干貨 2016-10-30
  • 通配符、正則表達式小計

    基本通配符:    *: 匹配任意長度的任意字符;    ?: 匹配任意的單個字符;    []: 匹配指定范圍內的任意單個字符;    [^]: 匹配非指定范圍內的任意單個字符;   簡單示例:   &nbs…

    Linux干貨 2017-03-16
欧美性久久久久