詳解MongoDB管理命令

chenfeng發表於2016-07-28
MongoDB是一個NoSQL資料庫系統:一個資料庫可以包含多個集合(Collection),每個集合對應於關聯式資料庫中的表;而每個集合中可以儲存一組由列標識的記錄,列是可以自由定義的,非常靈活,由一組列標識的實體的集合對應於關聯式資料庫表中的行。下面透過熟悉MongoDB的基本管理命令,來了解MongoDB提供的DBMS的基本功能和行為。 
MongoDB命令幫助系統 
在安裝MongoDB後,啟動伺服器程式(mongod),可以透過在客戶端命令mongo實現對MongoDB的管理和監控。看一下MongoDB的命令幫助系統:
 root@dev:~# mongo
 MongoDB shell version: ..
 connecting to: test
 > help
     db.help()          help on db methods
     db.mycoll.help()       help on collection methods
     rs.help()          help on replica set methods
     help connect         connecting to a db help
     help admin          administrative help
     help misc          misc things to know
     help mr           mapreduce 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 >= ms
     use        set current database
     db.foo.find()        list objects in collection foo
     db.foo.find( { a : } )   list objects in foo where a == 
     it              result of the last line evaluated; use to further iterate
     DBQuery.shellBatchSize = x  set default number of items to display on shell
     exit             quit the mongo shell 
這是MongoDB最頂層的命令列表,主要告訴我們管理資料庫相關的一些抽象的範疇:資料庫操作幫助、集合操作幫助、管理幫助。如果你想了解資料庫操作更詳細的幫助命令,可以直接使用db.help(),
如下所示:
 db.help()
 DB methods:
     db.addUser(username, password[, readOnly=false])
     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() - deprecated
     db.getProfilingStatus() - returns if profiling is on and slow threshold 
     db.getReplicationInfo()
     db.getSiblingDB(name) get the db at the same server as this one
     db.isMaster() check replica primary status
     db.killOp(opid) kills the current operation in the db
     db.listCommands() lists all the db commands
     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 : }
     db.serverStatus()
     db.setProfilingLevel(level,) =off =slow =all
     db.shutdownServer()
     db.stats()
     db.version() current version of the server
     db.getMongo().setSlaveOk() allow queries on a replication slave server 
對資料庫進行管理和操作的基本命令,可以從上面獲取到。如果想要得到更多,而且每個命令的詳細用法,可以使用上面列出的db.listCommands()查詢。
另一個比較基礎的是對指定資料庫的集合進行操作、管理和監控,可以透過查詢db.mycoll.help()獲取到:
db.mycoll.help()
 DBCollection help
     db.mycoll.find().help() - show DBCursor help
     db.mycoll.count()
     db.mycoll.dataSize()
     db.mycoll.distinct( key ) - eg. db.mycoll.distinct( 'x' )
     db.mycoll.drop() drop the collection
     db.mycoll.dropIndex(name)
     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:} , {name:, x:} )
     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.mapReduce( mapFunction , reduceFunction , )
     db.mycoll.remove(query)
     db.mycoll.renameCollection( newName , ) renames the collection.
     db.mycoll.runCommand( name , ) 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])
     db.mycoll.validate() - SLOW
     db.mycoll.getShardVersion() - only for use with sharding 
有關資料庫和集合管理的相關命令,是最基礎和最常用的,如集合查詢、索引操作等。
基本命令及例項 
下面透過實際的例子來演示一些常見的命令:
(一)基本命令 
1、show dbs
顯示當前資料庫伺服器上的資料庫
2、use pagedb
 切換到指定資料庫pagedb的上下文,可以在此上下文中管理pagedb資料庫以及其中的集合等
3、show collections
顯示資料庫中所有的集合(collection)
4、db.serverStatus()  
檢視資料庫伺服器的狀態。示例如下所示:
{
     "host" : "dev",
     "version" : "..",
     "process" : "mongod",
     "uptime" : ,
     "uptimeEstimate" : ,
     "localTime" : ISODate("--T::.Z"),
     "globalLock" : {
         "totalTime" : ,
         "lockTime" : ,
         "ratio" : .,
         "currentQueue" : {
             "total" : ,
             "readers" : ,
             "writers" : 
         },
         "activeClients" : {
             "total" : ,
             "readers" : ,
             "writers" : 
         }
     },
     "mem" : {
         "bits" : ,
         "resident" : ,
         "virtual" : ,
         "supported" : true,
         "mapped" : 
     },
     "connections" : {
         "current" : ,
         "available" : 
     },
     "extra_info" : {
         "note" : "fields vary by platform",
         "heap_usage_bytes" : ,
         "page_faults" : 
     },
     "indexCounters" : {
         "btree" : {
             "accesses" : ,
             "hits" : ,
             "misses" : ,
             "resets" : ,
             "missRatio" : .
         }
     },
     "backgroundFlushing" : {
         "flushes" : ,
         "total_ms" : ,
         "average_ms" : .,
         "last_ms" : ,
         "last_finished" : ISODate("--T::.Z")
     },
     "cursors" : {
         "totalOpen" : ,
         "clientCursors_size" : ,
         "timedOut" : 
     },
     "network" : {
         "bytesIn" : ,
         "bytesOut" : ,
         "numRequests" : 
     },
     "opcounters" : {
         "insert" : ,
         "query" : ,
         "update" : ,
         "delete" : ,
         "getmore" : ,
         "command" : 
     },
     "asserts" : {
         "regular" : ,
         "warning" : ,
         "msg" : ,
         "user" : ,
         "rollovers" : 
     },
     "writeBacksQueued" : false,
     "ok" : 
 } 
有時,透過檢視資料庫伺服器的狀態,可以判斷資料庫是否存在問題,如果有問題,如資料損壞,可以及時執行修復。
5、查詢指定資料庫統計資訊
use fragment
db.stats()


查詢結果示例如下所示:
db.stats()
 {
         "db" : "fragment",
         "collections" : ,
         "objects" : ,
         "avgObjSize" : .,
         "dataSize" : ,
         "storageSize" : ,
         "numExtents" : ,
         "indexes" : ,
         "indexSize" : ,
         "fileSize" : ,
         "ok" : 
 } 
顯示fragment資料庫的統計資訊。
6、查詢指定資料庫包含的集合名稱列表
db.getCollectionNames()


結果如下所示:
db.getCollectionNames()
 [
     "u",
     "baseSe",
     "bytravel",
     "daodao",
     "goeu",
     "lotour",
     "lvping",
     "mafengwo",
     "sina",
     "sohu",
     "system.indexes"
 ] 
(二)基本DDL和DML
 1、建立資料庫
如果你習慣了關係型資料庫,你可能會尋找相關的建立資料庫的命令。在MongoDB中,你可以直接透過use dbname來切換到這個資料庫上下文下面,系統會自動延遲建立該資料庫,例如:
 show dbs
 admin  .GB
 local  (empty)
 pagedb .GB
 test  .GB
 use LuceneIndexDB
 switched to db LuceneIndexDB
 show dbs
 admin  .GB
 local  (empty)
 pagedb .GB
 test  .GB
 db
 LuceneIndexDB
 db.storeCollection.save({'version':'.', 'segment':'eol'})
 show dbs
 LuceneIndexDB  .GB
 admin  .GB
 local  (empty)
 pagedb .GB
 test  .GB
可見,在use指定資料庫後,並且向指定其中的一個集合並插入資料後,資料庫和集合都被建立了。
2、刪除資料庫
直接使用db.dropDatabase()即可刪除資料庫。
3、建立集合
可以使用命令db.createCollection(name, { size : ..., capped : ..., max : ... } )建立集合,示例如下所示:
4、刪除集合
刪除集合,可以執行db.mycoll.drop()。
5、插入更新記錄
直接使用集合的save方法,如下所示:
 db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'}) 


更新記錄,使用save會將原來的記錄值進行覆蓋實現記錄更新。
6、查詢一條記錄
使用findOne()函式,引數為查詢條件,可選,系統會隨機查詢獲取到滿足條件的一條記錄(如果存在查詢結果數量大於等於1)示例如下所示: 
7、查詢多條記錄 
使用find()函式,引數指定查詢條件,不指定條件則查詢全部記錄。
8、刪除記錄
使用集合的remove()方法,引數指定為查詢條件,示例如下所示:
 db.storeCollection.remove({'version':'.'})
 db.storeCollection.findOne()
 null 
9、建立索引
可以使用集合的ensureIndex(keypattern[,options])方法,示例如下所示: 
use pagedb
switched to db pagedb
db.page.ensureIndex({'title':, 'url':-})
db.system.indexes.find()
 { "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : }, "v" : }
 { "name" : "_id_", "ns" : "pagedb.system.users", "key" : { "_id" : }, "v" : }
 { "_id" : ObjectId("efcfcaccd"), "ns" : "pagedb.page", "key" : {"title" : , "url" : - }, "name" : "title__url_-", "v" : }
 上述,ensureIndex方法引數中,數字1表示升序,-1表示降序。
使用db.system.indexes.find()可以查詢全部索引。
10、查詢索引
我們為集合建立的索引,那麼可以透過集合的getIndexes()方法實現查詢,示例如下所示: 
 db.page.getIndexes()
 [
     {
         "name" : "_id_",
         "ns" : "pagedb.page",
         "key" : {
             "_id" : 
         },
         "v" : 
     },
     {
         "_id" : ObjectId("efcfcaccd"),
         "ns" : "pagedb.page",
         "key" : {
             "title" : ,
             "url" : -
         },
         "name" : "title__url_-",
         "v" : 
     }
 ]
當然,如果需要查詢系統中全部的索引,可以使用db.system.indexes.find()函式。
 11、刪除索引
 刪除索引給出了兩個方法: 
db.mycoll.dropIndex(name)
  db.mycoll.dropIndexes() 
第一個透過指定索引名稱,第二個刪除指定集合的全部索引。
 12、索引重建
可以透過集合的reIndex()方法進行索引的重建,示例如下所示:
use fragment
db.baseSe.count()
統計結果,如下所示: 
 use fragment
 switched to db fragment
 db.baseSe.count()
上述統計了資料庫fragment的baseSe集合中記錄數。
 14、查詢並統計結果記錄數
 use fragment
db.baseSe.find().count()
find()可以提供查詢引數,然後查詢並統計結果,如下所示: 
15、查詢指定資料庫的集合當前可用的儲存空間
use fragment
db.baseSe.storageSize()
142564096
16、查詢指定資料庫的集合分配的儲存空間
db.baseSe.totalSize()
 144096000
上述查詢結果中,包括為集合(資料及其索引儲存)分配的儲存空間。
(三)啟動與終止 
1、正常啟動
mongod --dbpath /usr/mongo/data --logfile /var/mongo.log
說明:
指定資料儲存目錄和日誌目錄,如果採用安全認證模式,需要加上--auth選項,如:
mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log 
2、以修復模式啟動
mongod --repair
以修復模式啟動資料庫。
實際很可能資料庫資料損壞或資料狀態不一致,導致無法正常啟動MongoDB伺服器,根據啟動資訊可以看到需要進行修復。或者執行:
mongod -f /etc/mongodb.conf --repair
3、終止伺服器程式
db.shutdownServer()


終止資料庫伺服器程式。或者,可以直接kill掉mongod程式即可。
(四)安全管理 
1、以安全認證模式啟動 
mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log


使用--auth選項啟動mongod程式即可啟用認證模式。
或者,也可以修改/etc/mongodb.conf,設定auth=true,重啟mongod程式。
2、新增使用者
db.addUser("admin", ",%F23_kj~00Opoo0+\/")
新增資料庫使用者,新增成功,則顯示結果如下所示:
db.auth("admin", ",%F23_kj~00Opoo0+\/")
資料庫安全認證。認證成功顯示結果:
 {
     "user" : "admin",
     "readOnly" : false,
     "pwd" : "debfcbabbecd"
 } 
如果是認證使用者,執行某些命令,可以看到正確執行結果,如下所示:
4、為資料庫寫資料(同步到磁碟)加鎖
db.runCommand({fsync:1,lock:1})
說明:
該操作已經對資料庫上鎖,不允許執行寫資料操作,一般在執行資料庫備份時有用。執行命令,結果示例如下:
5、檢視當前鎖狀態
db.currentOp()
說明:
查詢結果如下所示:
6、解鎖
 use admin
db.$cmd.sys.unlock.findOne()


說明:
執行解鎖,結果如下所示:
db.currentOp()
狀態資訊如下:
(五)資料備份、恢復與遷移管理 
1、備份全部資料庫
mkdir testbak
cd testbak
mongodump
說明:預設備份目錄及資料檔案格式為./dump/[databasename]/[collectionname].bson
2、備份指定資料庫
mongodump -d pagedb
說明:備份資料庫pagedb中的資料。
3、備份一個資料庫中的某個集合
mongodump -d pagedb -c page
說明:備份資料庫pagedb的page集合。
4、恢復全部資料庫
cd testbak
mongorestore --drop
說明:將備份的所有資料庫恢復到資料庫,--drop指定恢復資料之前刪除原來資料庫資料,否則會造成回覆後的資料中資料重複。
5、恢復某個資料庫的資料
cd testbak
mongorestore -d pagedb --drop


說明:將備份的pagedb的資料恢復到資料庫。
6、恢復某個資料庫的某個集合的資料
cd testbak
mongorestore -d pagedb -c page --drop
說明:將備份的pagedb的的page集合的資料恢復到資料庫。
7、向MongoDB匯入資料
mongoimport -d pagedb -c page --type csv --headerline --drop < csvORtsvFile.csv


說明:將檔案csvORtsvFile.csv的資料匯入到pagedb資料庫的page集合中,使用cvs或tsv檔案的列名作為集合的列名。需要注意的是,使用--headerline選項時,只支援csv和tsv檔案。
--type支援的型別有三個:csv、tsv、json
其他各個選項的使用,可以檢視幫助:
mongoexport -d pagedb -c page -q {} -f _id,title,url,spiderName,pubDate --csv > pages.csv


說明:將pagedb資料庫中page集合的資料匯出到pages.csv檔案,其中各選項含義:
-f 指定cvs列名為_id,title,url,spiderName,pubDate
-q 指定查詢條件
其他各個選項的使用,可以檢視幫助:
如果上面的選項-q指定一個查詢條件,需要使用單引號括起來。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15498/viewspace-2122689/,如需轉載,請註明出處,否則將追究法律責任。