mongoDB系列之(三):mongoDB 分區

來源:互聯網
上載者:User

標籤:

1. monogDB的分區(Sharding)

分區是mongoDB針對TB層級以上的資料量,採用的一種資料存放區方式。

mongoDB採用將集合進行拆分,然後將拆分的資料均攤到幾個mongoDB執行個體上的一種解決方案。

分區模式下,mongoDB執行個體分為三種:

shards: 儲存資料的mongoDB

config: 儲存設定的monogDB

routing(mongos): 負責分區處理的mongoDB

2. 配置分區2.1 實驗環境

1 mongos, 1 config, 2 shard

config:  test166:27019mongos:  test166:27020shards:  test166:27017,test167:27017

mongoDB都是單台構成,沒有使用複本集

2.2 啟動config

在test166上啟動config執行個體,連接埠27019

# mongod --configsvr --dbpath /var/lib/mongo-c --port 27019
2.3 啟動 mongos

在test166上啟動routing執行個體,連接埠27020

# mongos --configdb test166:27019 --port 27020
2.4 啟動 shards

在test166和test167上分別啟動shards

# /etc/init.d/mongod start
2.5 添加shards

串連monogs

# mongo --port 27020

添加shards

mongos> use adminmongos> sh.addShard( "test166:27017" )mongos> sh.addShard( "test167:27017" )

確認

mongos> db.runCommand({listshards:1})
2.6 開啟分區

對指定的庫開啟sharding

mongos> sh.enableSharding("new")

指定分區的片鍵

片鍵有兩種模式:hash模式,range模式

2.6.1 使用hash模式分區
mongos> sh.shardCollection( "new.person", { "_id": "hashed" } )

插入資料確認

mongos> use newmongos> for(var i=0;i<10;i++){db.person.insert({name:"bluejoe"+i});}

使用hash模式,記錄在各片上的分布比較平均

2.6.2 使用range模式分區
mongos> sh.shardCollection( "new.person2", { "name": 1 } )

插入資料確認

mongos> use newmongos> for(var i=0;i<100;i++){db.person2.insert({name:"jack"+i});}
2.7 確認分區情況
mongos> sh.status()或mongos> db.printShardingStatus()

在各shard上確認資料分布情況(hash模式)

> use new> db.person.find()

test166:27017上的資料分布情況

test167:27017上的資料分布情況

2.8 其他

要分區的庫原來有資料的情況下,先建index,然後再指定片鍵

mongos> sh.enableSharding("new2")mongos> use new2mongos> db.user2.createIndex( { "username": 1 } )mongos> sh.shardCollection( "new2.user2", { "username": 1 } )
3. 後記

本次測試環境使用mongoDB單台構成,沒有使用複本集,使用複本集時的分區配置和上面類似,在此不詳述。

mongoDB系列之(三):mongoDB 分區

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.