天天看點

mongodb資料庫的安裝、基本操作、資料備份整理

mongodb資料庫

1.安裝

  1)下載下傳源碼包:

    http://downloads.mongodb.org/linux/mongodb-linux-x86_64-2.6.4.tgz

  2)解壓縮源碼包:

    tar -zxvf /usr/local/src/mongodb-linux-x86_64-2.6.4.tgz

  3)mkdir -p /usr/local/mongodb

    cp -R -n /usr/local/src/mongodb-linux-x86_64-2.6.4/* /usr/local/mongodb/

  4)設定環境變量:(此方法隻對目前登入使用者有效)

    vim ~/.bash_profile

       export PATH=/usr/local/mongodb/bin:$PATH

    source ~/.bash_profile #使新配置環境生效

    =================================================

    全局使用者環境配置

    vim /etc/profile

    source /etc/profile

2.啟動mongodb

  1)建立資料庫的資料目錄和日志目錄

    mkdir -p /home/data/mongodb/data

    mkdir -p /home/data/mongodb/logs

    ==============================================================================================================

    常用mongod指令參數:

    -h [ --help ]             檢視幫助

    --version                 檢視版本資訊

    -f [ --config ] arg       指定配置檔案

    --port arg                指定端口号

    --dbpath arg (=/data/db/) 指定資料存放目錄

    --quiet                   指定靜默模式

    --logpath arg             指定log檔案存放目錄

    --logappend               指定日志是以追加的方式寫入日志檔案

    --fork                    以建立子程序的方式運作

    --cpu                     周期性的顯示cpu和io的使用情況

    --noauth                  無認證模式運作

    --auth                    認證模式運作

    --objcheck                對用戶端輸入資料的有效性檢查

    --quota                   開啟資料庫配額的管理

    --quotaFiles arg          規定每個資料庫允許的檔案數

    --nocursors               diagnostic/debugging option 調試診斷選項

    --nohints                 ignore query hints 忽略查詢命中率

    --nohttpinterface         disable http interface 關閉http接口,預設是28017

    --noscripting             disable scripting engine 關閉腳本引擎

    --noprealloc              disable data file preallocation 關閉資料庫檔案大小預配置設定

    --smallfiles              use a smaller default file size 使用較小的預設檔案大小

    --nssize arg (=16)        .ns file size (in MB) for new databases 新資料庫ns檔案的預設大小

    --diaglog arg             0=off 1=W 2=R 3=both 7=W+some reads 提供的方式,是隻讀,隻寫,

                              還是讀寫都行,還是主要寫+部分的讀模式

    --sysinfo                 print some diagnostic system information 列印系統診斷資訊

    --upgrade                 upgrade db if needed 如果需要就更新資料庫

    --repair                  run repair on all dbs 修複所有的資料庫

    --notablescan             do not allow table scans 不運作表掃描

    --syncdelay arg (=60)     seconds between disk syncs (0 for never) 系統同步重新整理磁盤的時間,

                              預設是60s 

    Replication options:

    --master                  master mode 主複制模式

    --slave                   slave mode 從複制模式

    --source arg              when slave: specify master as <server:port> 當為從時,指定主的位址和端口

    --only arg                when slave: specify a single database to replicate 當為從時,指定需要從主複制的單一庫

    --pairwith arg            address of server to pair with  

    --arbiter arg             address of arbiter server 仲裁伺服器,在主主中和pair中用到

    --autoresync              automatically resync if slave data is stale 自動同步從的資料

    --slavedelay arg          specify delay (in seconds) to be used when applying master ops to slave 指從複制檢測的間隔

    --oplogSize arg           size limit (in MB) for op log 指定記錄檔的大小

    --opIdMem arg             size limit (in bytes) for in memory storage of op ids指定存儲記錄檔的記憶體大小

    Sharding options:

    --configsvr           declare this is a config db of a cluster 指定shard中的配置伺服器

    --shardsvr            declare this is a shard db of a cluster 指定shard伺服器

   =====================================================================================================================

  2)開啟服務

    /usr/local/mongodb/bin/mongod --dbpath /home/data/mongodb/data/ --logpath=/home/data/mongodb/logs/mongod.log --logappend --auth --port=27017 --fork &

    ###指定資料存放目錄、日志目錄及檔案名稱、日志寫入采用追加的形式、背景執行

    #配置環境之後,直接這樣使用:

      mongod --dbpath /home/data/mongodb/data/ --logpath=/home/data/mongodb/logs/mongod.log --logappend --auth --port=27017 --fork &

    ###檢視程序運作情況 ps aux|grep [m]ongod

  3)設定開機自啟動

    将mongodb啟動項目追加入rc.local保證mongodb在伺服器開機時啟動

    echo "/usr/local/mongodb/bin/mongod --dbpath /home/data/mongodb/data/ --logpath=/home/data/mongodb/logs/mongod.log --logappend --auth --port=27017 --fork" >> /etc/rc.local

  4)使用自帶用戶端連接配接

    /usr/local/mongodb/bin/mongo

    ========================

      > show databases;

      admin  (empty)

      local  0.078GB

     若資料庫出現如不能連上,則是一個data目錄下的mongod.lock檔案的問題,可以用如下的修複的指令,

     mongod --repair

  4)關閉服務:

    killall mongod  [kill [pid]]

3.mongod資料的使用

  1)使用者管理(備注:首先要進入一個資料庫:>use test;)

    添加使用者:

     >db.addUser("root","1234");預設是擁有weiw資料庫所有權限(讀寫權限false)

     >db.addUser("swht","1234",true);擁有這個資料庫的隻讀權限

  =====================================================================

   > db.addUser("root","1234");

   WARNING: The 'addUser' shell helper is DEPRECATED. Please use 'createUser' instead

   Successfully added user: { "user" : "root", "roles" : [ "dbOwner" ] }

   > db.addUser("swht","1234",true);

   Successfully added user: { "user" : "swht", "roles" : [ "read" ] }

  ======================================================================

    檢視所有使用者:

     >db.system.users.find();

    删除使用者:

     >db.system.users.remove({user:"root"});

     >db.removeUser("root");

    建立超級使用者:

     進入admin資料庫

      >use admin

     在admin中建立的所有使用者都是超級使用者,可以操作任何的資料庫

      >db.addUser("admin","admin");預設是擁有所有資料庫所有權限

      >db.addUser("admin1","admin",true);擁有所有資料庫的隻讀權限

  1)建立集合集

   =====================================================

    > db.user.insert({uid:1,username:"Falcon.C",age:25});

    WriteResult({ "nInserted" : 1 })

    > db.user.insert({uid:2,username:"swht",age:24});

   ======================================================    

  2)查詢資料:

   ======================================================

    > db.user.find();

     { "_id" : ObjectId("5480085a2fcd6b18cad71ddd"), "uid" : 1, "username" : "Falcon.C", "age" : 25 }

     { "_id" : ObjectId("5480088e2fcd6b18cad71dde"), "uid" : 2, "username" : "swht", "age" : 24 }

    > db.user.find({uid:1});

   ======================================================   

    > show databases;

    admin  (empty)

    local  0.078GB

    test   0.078GB

   備注:查詢資料的方式很豐富,有類似于SQL的條件查詢,還支援豐富的查詢還有limit ,sort ,findOne,distinct等

  3)更新資料

   更新的條件還有$unset、$push 、$pushAll 、$pop 、$pull 、$pullAll

  4)擷取幫助:

   ==========================================================

   > help

   HELP

         show dbs                     show database names

         show collections             show collections in current database

         show users                   show users in current database

         show profile                 show most recent system.profile entries with time >= 1ms

         use <db name>                set curent database to <db name>

         db.help()                    help on DB methods

         db.foo.help()                help on collection methods

         db.foo.find()                list objects in collection foo

         db.foo.find( { a : 1 } )     list objects in foo where a == 1

         it                           result of the last line evaluated; use to further iterate

   > db.help();

         DB methods:

         db.addUser(username, password) 添加資料庫授權使用者

         db.auth(username, password)    通路認證

         db.cloneDatabase(fromhost) 克隆資料庫

         db.commandHelp(name) returns the help for the command

         db.copyDatabase(fromdb, todb, fromhost) 複制資料庫

         db.createCollection(name, { size : ..., capped : ..., max : ... } ) 建立表

         db.currentOp() displays the current operation in the db

         db.dropDatabase()        删除目前資料庫

         db.eval(func, args) run code server-side

         db.getCollection(cname) same as db['cname'] or db.cname

         db.getCollectionNames()        擷取目前資料庫的表名

         db.getLastError() - just returns the err msg string

         db.getLastErrorObj() - return full status object

         db.getMongo() get the server connection object

         db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair

         db.getName()

         db.getPrevError()

         db.getProfilingLevel()

         db.getReplicationInfo()

         db.getSisterDB(name) get the db at the same server as this onew

         db.killOp() kills the current operation in the db

         db.printCollectionStats()   列印各表的狀态資訊

         db.printReplicationInfo()        列印主資料庫的複制狀态資訊

         db.printSlaveReplicationInfo()        列印從資料庫的複制狀态資訊

         db.printShardingStatus()                列印分片狀态資訊

         db.removeUser(username) 删除資料庫使用者

         db.repairDatabase() 修複資料庫

         db.resetError()

         db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into { cmdObj : 1 }

         db.setProfilingLevel(level) 0=off 1=slow 2=all

         db.shutdownServer()

         db.version() current version of the server

   > db.foo.help(); user為表名

         DBCollection help

         db.foo.count()                統計表的行數

         db.foo.dataSize()        統計表資料的大小

         db.foo.distinct( key ) - eg. db.foo.distinct( 'x' )                按照給定的條件除重

         db.foo.drop() drop the collection 删除表

         db.foo.dropIndex(name) 删除指定索引

         db.foo.dropIndexes() 删除所有索引

         db.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups 增加索引

         db.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return. 根據條件查找資料

         e.g. db.foo.find( { x : 77 } , { name : 1 , x : 1 } )

         db.foo.find(...).count()

         db.foo.find(...).limit(n) 根據條件查找資料并傳回指定記錄數

         db.foo.find(...).skip(n)

         db.foo.find(...).sort(...) 查找排序

         db.foo.findOne([query]) 根據條件查詢隻查詢一條資料

         db.foo.getDB() get DB object associated with collection 傳回表所屬的庫

         db.foo.getIndexes() 顯示表的所有索引

         db.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } ) 根據條件分組

         db.foo.mapReduce( mapFunction , reduceFunction , <optional params> )

         db.foo.remove(query) 根據條件删除資料

         db.foo.renameCollection( newName ) renames the collection 重命名表

         db.foo.save(obj) 儲存資料

         db.foo.stats() 檢視表的狀态

         db.foo.storageSize() - includes free space allocated to this collection 查詢配置設定到表空間大小

         db.foo.totalIndexSize() - size in bytes of all the indexes 查詢所有索引的大小

         db.foo.totalSize() - storage allocated for all data and indexes 查詢表的總大小

         db.foo.update(query, object[, upsert_bool]) 根據條件更新資料

         db.foo.validate() - SLOW 驗證表的詳細資訊

         db.foo.getShardVersion() - only for use with sharding

4.資料庫備份與還原

  1)正常的檔案json資料導出與導入

  #資料導出 mongoexport

  /usr/local/mongodb/bin/mongoexport  -h 192.168.1.200 -u root -p1234 -d my_mongodb -c user -o data_bak.dat

  #導出某個資料庫中的某張表并存放到指定目錄的指定檔案

  ==============================================

  參數說明:

   -h 指定資料庫主機位址

   -u 指定使用者名

   -p 指定使用者名密碼

   -d 指明使用的庫, 本例中為” my_mongodb”

   -c 指明要導出的表, 本例中為”user”

   -o 指明要導出的檔案名, 本例中為”data_bak.dat”

  ===============================================

   #檢視集合(資料表)

    show collections

    删除集合

    db.table_name.drop()

   #檢視資料庫

    show dbs

    删除整個庫

    > show dbs

    admin  0.078GB

    > db

    test

    > db.ttlsa_com.getDB()

    > show collections

    system.indexes

    user

    > db.dropDatabase()

    { "dropped" : "test", "ok" : 1 }

  #資料導入mongoimport

   /usr/local/mongodb/bin/mongoimport -h 192.168.1.200 -u root -p1234 -d my_mongodb -c user  data_bak.dat

   #導入資料,指定資料庫、資料表&&備份的檔案路徑

   2)使用mongodump進行備份

   /usr/local/mongodb/bin/mongodump -h 127.0.0.1:27017 -u root -p1234 -d test -o /opt/test.bak

   ===============================================

   -h:MongDB所在伺服器位址和端口

   -d:需要備份的資料庫執行個體

   -o:備份的資料存放位置,在備份完成後,系統自動在dump目錄下建立一個lietou目錄,這個目錄裡面存放該資料庫執行個體的備份資料。

   ========================================

   /usr/local/mongodb/bin/mongorestore -h 127.0.0.1:27017-u root -p1234 -d test  --directoryperdb /opt/test.bak/test

   #還原的時候後面要加上備份資料庫的名字,因為備份時系統會自動将所備份的資料庫檔案放到一個與資料庫名稱相同的檔案目錄下,而這個目錄就在我們備份檔案的目錄

   =================================================

   -h:MongoDB所在伺服器位址

   -d:需要恢複的資料庫執行個體,當然這個名稱也可以和備份時候的不一樣,比如test2  

   --directoryperdb:備份資料所在位置,這裡為什麼要多加一個資料庫名稱   

   --drop:恢複的時候,先删除目前資料,然後恢複備份的資料。就是說,恢複後,備份後添加修改的資料都會被删除,慎用哦!

  ====================================================

  導出庫:

  mongodump -h IP --port 端口 -u 使用者名 -p 密碼 -d 資料庫 -o 檔案存在路徑 

    如果沒有使用者誰,可以去掉-u和-p。

    如果導出本機的資料庫,可以去掉-h。

    如果是預設端口,可以去掉--port。

    如果想導出所有資料庫,可以去掉-d。

  恢複庫:

  mongorestore -h IP --port 端口 -u 使用者名 -p 密碼 -d 資料庫 --drop 檔案存在路徑

    --drop的意思是,先删除所有的記錄,然後恢複。

                                                                   [email protected]

                                                                      2014-12-05整理分享

本文轉自 南非波波 51CTO部落格,原文連結:http://blog.51cto.com/nanfeibobo/1586744,如需轉載請自行聯系原作者