1. 程式人生 > >MongoDB學習(四)MongoDB 日常運維操作命令

MongoDB學習(四)MongoDB 日常運維操作命令

1.MongoDB 命令幫助系統

在安裝MongoDB後,啟動伺服器程序(mongod),可以通過在客戶端命令mongo實現對MongoDB的管理和監控。

1.1MongoDB的命令幫助系統

> help
    db.help()                    help on db methods
    db.mycoll.help()             help on collection methods
    sh.help()                    sharding helpers
    rs.help()                    replica set helpers


    help admin                   administrative help
    help connect                 connecting to a db help
    help keys                    key shortcuts
    help misc                    misc things to know
    help mr                      mapreduce
    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
    show logs                    show the accessible logger names
    show log [name]              prints out the last segment of log in memory, 'global' is default
    use <db_name>                set current database
    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
    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.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
    db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
    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.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
    db.createUser(userDocument)
    db.currentOp() displays currently executing operations in the db
    db.dropDatabase()
    db.eval() - deprecated
    db.fsyncLock() flush data to disk and lock server for backups
    db.fsyncUnlock() unlocks server following a db.fsyncLock()
    db.getCollection(cname) same as db['cname'] or db.cname
    db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
    db.getCollectionNames()
    db.getLastError() - just returns the err msg string
    db.getLastErrorObj() - return full status object
    db.getLogComponents()
    db.getMongo() get the server connection object
    db.getMongo().setSlaveOk() allow queries on a replication slave server
    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.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
    db.hostInfo() get details about the server's host
    db.isMaster() check replica primary status
    db.killOp(opid) kills the current operation in the db
    db.listCommands() lists all the db commands
    db.loadServerScripts() loads all the scripts in db.system.js
    db.logout()
    db.printCollectionStats()
    db.printReplicationInfo()
    db.printShardingStatus()
    db.printSlaveReplicationInfo()
    db.dropUser(username)
    db.repairDatabase()
    db.resetError()
    db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into {cmdObj: 1}
    db.serverStatus()
    db.setLogLevel(level,<component>)
    db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
    db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
    db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
    db.setVerboseShell(flag) display extra information in shell output
    db.shutdownServer()
    db.stats()
    db.version() current version of the server
>
對資料庫進行管理和操作的基本命令,可以從上面獲取到。如果想要得到更多,而且每個命令的詳細用法,可以使用上面列出的db.listCommands()查詢。另一個比較基礎的是對指定資料庫的集合進行操作、管理和監控,可以通過查詢db.mycoll.help()獲取到:

> db.mycoll.help()
DBCollection help
    db.mycoll.find().help() - show DBCursor help
    db.mycoll.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
    db.mycoll.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    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.createIndex(keypattern[,options])
    db.mycoll.createIndexes([keypatterns], <options>)
    db.mycoll.dataSize()
    db.mycoll.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
    db.mycoll.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
    db.mycoll.distinct( key, query, <optional params> ) - e.g. db.mycoll.distinct( 'x' ), optional parameters are: maxTimeMS
    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]) - DEPRECATED, use createIndex() instead
    db.mycoll.explain().help() - show explain help
    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], [fields], [options], [readConcern])
    db.mycoll.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
    db.mycoll.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.mycoll.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.mycoll.getDB() get DB object associated with collection
    db.mycoll.getPlanCache() get query plan cache associated with collection
    db.mycoll.getIndexes()
    db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
    db.mycoll.insert(obj)
    db.mycoll.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
    db.mycoll.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
    db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> )
    db.mycoll.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
    db.mycoll.remove(query)
    db.mycoll.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
    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({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
    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.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.mycoll.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
    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
    db.mycoll.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
    db.mycoll.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
    db.mycoll.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
    db.mycoll.latencyStats() - display operation latency histograms for this collection
>
> db.test.help()   ---db.表名.help()
DBCollection help
    db.test.find().help() - show DBCursor help
    db.test.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
    db.test.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    db.test.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.
    db.test.convertToCapped(maxBytes) - calls {convertToCapped:'test', size:maxBytes}} command
    db.test.createIndex(keypattern[,options])
    db.test.createIndexes([keypatterns], <options>)
    db.test.dataSize()
    db.test.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
    db.test.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
    db.test.distinct( key, query, <optional params> ) - e.g. db.test.distinct( 'x' ), optional parameters are: maxTimeMS
    db.test.drop() drop the collection
    db.test.dropIndex(index) - e.g. db.test.dropIndex( "indexName" ) or db.test.dropIndex( { "indexKey" : 1 } )
    db.test.dropIndexes()
    db.test.ensureIndex(keypattern[,options]) - DEPRECATED, use createIndex() instead
    db.test.explain().help() - show explain help
    db.test.reIndex()
    db.test.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                  e.g. db.test.find( {x:77} , {name:1, x:1} )
    db.test.find(...).count()
    db.test.find(...).limit(n)
    db.test.find(...).skip(n)
    db.test.find(...).sort(...)
    db.test.findOne([query], [fields], [options], [readConcern])
    db.test.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
    db.test.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.test.findOneAndUpdate( filter, update, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.test.getDB() get DB object associated with collection
    db.test.getPlanCache() get query plan cache associated with collection
    db.test.getIndexes()
    db.test.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
    db.test.insert(obj)
    db.test.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
    db.test.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
    db.test.mapReduce( mapFunction , reduceFunction , <optional params> )
    db.test.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
    db.test.remove(query)
    db.test.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.test.renameCollection( newName , <dropTarget> ) renames the collection.
    db.test.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
    db.test.save(obj)
    db.test.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
    db.test.storageSize() - includes free space allocated to this collection
    db.test.totalIndexSize() - size in bytes of all the indexes
    db.test.totalSize() - storage allocated for all data and indexes
    db.test.update( query, object[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi
    db.test.updateOne( filter, update, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.test.updateMany( filter, update, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j
    db.test.validate( <full> ) - SLOW
    db.test.getShardVersion() - only for use with sharding
    db.test.getShardDistribution() - prints statistics about data distribution in the cluster
    db.test.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
    db.test.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
    db.test.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
    db.test.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
    db.test.latencyStats() - display operation latency histograms for this collection
>

1.2速查表


庫操作
切換或使用資料庫use mymongodb
看所有的庫show dbs
刪除當前使用資料庫db.dropDatabase()
克隆所有的庫到當前連線db.cloneDatabase(“192.160.1.1”)
複製指定的庫db.cloneDatabase(“sourcedb”,”targetdb”,”192.168.1.1”)
檢視當前資料庫db.getName()
當前資料庫狀態db.stats()
當前資料庫版本db.version()
檢視當前資料庫的連線db.getMongo()
使用者操作
新增使用者db.addUser(“user_name”, “password”, true)
使用者認證db.auth(“username”, “password”)
顯示所有使用者show users;
刪除使用者db.removeUser(“username”);
集合基本資訊
查詢集合的資料條數db.myCollection.count();
檢視資料空間大小db.myCollection.dataSize();
檢視集合所在的資料庫db.myCollection.getDB();
當前聚集的狀態db.myCollection.stats();
當前集合的總大小db.myCollection.totalSize();
集合儲存空間大小db.myCollection.storageSize();
Shard版本資訊db.myCollection.getShardVersion();
集合重新命名db.myCollection.renameCollection(“targetCollection”);
刪除集合db.myCollection.drop();
集合資料增刪改
新增記錄db.myCollection.save({mykey:”t_key”,myvalue:”t-value”});
刪除記錄db.myCollection.remove({mykey:”t_key”});
修改記錄db.myCollection.update({condition: xx}, {$set: {field: ‘changefield’}}, false, true);
查詢並修改記錄db.myCollection.findAndModify(query: {condition1: {gte: XX}},
    sort: {condition2: -1},
    update: {
set: {target1: 'yy'}, $inc: {target2: 2}}, remove: true});
集合資料查詢
查詢所有記錄db.myCollection.find();
查詢第一條記錄db.myCollection.findOne();
資料去重db.myCollection.distinct(“fieldname”);
數值區間查詢db.myCollection.find({numfield:{$gte:nn}});
字串查詢db.myCollection.find({targetfield:/ABC/});
指定欄位查詢db.myCollection.find({},{field1:’abc’,field2:nnn});
指定返回條數查詢db.myCollection.find().limit(m).skip(n);
排序db.myCollection.find().sort({targetfield:-1}); //降序
統計記錄數db.myCollection.find({target: n }).count();
索引操作
建立db.myCollection.ensureIndex({targetfield: 1});
查詢所有索引db.myCollection.getIndexes();
查詢所有索引大小db.myCollection.totalIndexSize();
查詢索引資訊db.myCollection.reIndex({targetfield: 1});
刪除指定索引db.myCollection.dropIndex(“targetfield”);
刪除所有索引db.myCollection.dropIndexes();
輔助命令
查詢錯誤資訊db.getPrevError();
清空錯誤資訊db.resetError();
各種幫助資訊help; db.help();db.myCollection.help();db.myCollection.find().help();rs.help();

1.3基本命令

1)show dbs顯示當前資料庫伺服器上的資料庫

2)use pagedb切換到指定資料庫pagedb的上下文,可以在此上下文中管理pagedb資料庫以及其中的集合等

3)show collections顯示資料庫中所有的集合(collection)

4)db.serverStatus() 檢視資料庫伺服器的狀態。有時,通過檢視資料庫伺服器的狀態,可以判斷資料庫是否存在問題,如果有問題,如資料損壞,可以及時執行修復。

5)查詢指定資料庫統計資訊use fragment db.stats()查詢結果示例如下所示:

> use fragment
switched to db fragment
> db.stats()
{
    "db" : "fragment",
    "collections" : 0,
    "objects" : 0,
    "avgObjSize" : 0,
    "dataSize" : 0,
    "storageSize" : 0,
    "numExtents" : 0,
    "indexes" : 0,
    "indexSize" : 0,
    "fileSize" : 0,
    "ok" : 1
}

6)查詢指定資料庫包含的集合名稱列表db.getCollectionNames()結果如下所示:

> db.getCollectionNames()  
[  
        "17u",  
        "baseSe",  
        "bytravel",  
        "daodao",  
        "go2eu",  
        "lotour",  
        "lvping",  
        "mafengwo",  
        "sina",  
        "sohu",  
        "system.indexes"  
]  

1.4基本DDL和DML

1)建立資料庫如果你習慣了關係型資料庫,你可能會尋找相關的建立資料庫的命令。在MongoDB中,你可以直接通過use dbname來切換到這個資料庫上下文下面,系統會自動延遲建立該資料庫,例如:

> show dbs  
local  0.078GB
> use LuceneIndexDB  
switched to db LuceneIndexDB
> show dbs 
local  0.078GB
> db 
LuceneIndexDB
> db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})
WriteResult({ "nInserted" : 1 })
> show dbs
LuceneIndexDB  0.078GB
local          0.078GB
> 

可見,在use指定資料庫後,並且向指定其中的一個集合並插入資料後,資料庫和集合都被建立了。

2)刪除資料庫直接使用db.dropDatabase()即可刪除資料庫。

3)建立集合可以使用命令db.createCollection(name, { size : ..., capped : ..., max : ... } )建立集合,示例如下所示:

> db.createCollection('replicationColletion', {'capped':true, 'size':10240, 'max':17855200}) 
{ "ok" : 1 }
> show collections  
replicationColletion
storeCollection
system.indexes

4)刪除集合刪除集合,可以執行db.mycoll.drop()。

5)插入更新記錄直接使用集合的save方法,如下所示:

> db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})
WriteResult({ "nInserted" : 1 })

更新記錄,使用save會將原來的記錄值進行覆蓋實現記錄更新。

6)查詢一條記錄使用findOne()函式,引數為查詢條件,可選,系統會隨機查詢獲取到滿足條件的一條記錄(如果存在查詢結果數量大於等於1)示例如下所示:

> db.storeCollection.findOne({'version':'3.5'})  
{
	"_id" : ObjectId("5a4c1733f5c45f057ae82292"),
	"version" : "3.5",
	"segment" : "e3ol6"
}

7)查詢多條記錄使用find()函式,引數指定查詢條件,不指定條件則查詢全部記錄。

8)刪除記錄使用集合的remove()方法,引數指定為查詢條件,示例如下所示:

> db.storeCollection.remove({'version':'3.5'})  
WriteResult({ "nRemoved" : 2 })
> db.storeCollection.findOne()  
null

9)建立索引可以使用集合的ensureIndex(keypattern[,options])方法,示例如下所示:

> use pagedb 
switched to db pagedb
> db.page.ensureIndex({'title':1, 'url':-1})  
{
    "createdCollectionAutomatically" : true,
    "numIndexesBefore" : 1,
    "numIndexesAfter" : 2,
    "ok" : 1
}
> db.system.indexes.find()  
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "pagedb.page" }
{ "v" : 1, "key" : { "title" : 1, "url" : -1 }, "name" : "title_1_url_-1", "ns" : "pagedb.page" }

上述,ensureIndex方法引數中,數字1表示升序,-1表示降序。使用db.system.indexes.find()可以查詢全部索引。

10)查詢索引我們為集合建立的索引,那麼可以通過集合的getIndexes()方法實現查詢,示例如下所示:

> db.page.getIndexes()  
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "pagedb.page"
	},
	{
		"v" : 1,
		"key" : {
			"title" : 1,
			"url" : -1
		},
		"name" : "title_1_url_-1",
		"ns" : "pagedb.page"
	}
]

當然,如果需要查詢系統中全部的索引,可以使用db.system.indexes.find()函式。

11)刪除索引刪除索引給出了兩個方法:

> db.mycoll.dropIndex(name) 
2018-01-02T23:45:50.155+0000 E QUERY    ReferenceError: name is not defined
    at (shell):1:21
> db.mycoll.dropIndexes()  
{ "ok" : 0, "errmsg" : "ns not found" }
> 

第一個通過指定索引名稱,第二個刪除指定集合的全部索引。

12)索引重建可以通過集合的reIndex()方法進行索引的重建,示例如下所示:

> db.page.reIndex()  
{
	"nIndexesWas" : 2,
	"nIndexes" : 2,
	"indexes" : [
		{
			"key" : {
				"_id" : 1
			},
			"name" : "_id_",
			"ns" : "pagedb.page"
		},
		{
			"key" : {
				"title" : 1,
				"url" : -1
			},
			"name" : "title_1_url_-1",
			"ns" : "pagedb.page"
		}
	],
	"ok" : 1
}

13)統計集合記錄數

> use fragment
switched to db fragment
> db.baseSe.count()
36749

上述統計了資料庫fragment的baseSe集合中記錄數。

14)查詢並統計結果記錄數

> use fragment
switched to db fragment
> db.baseSe.find().count()
36749

find()可以提供查詢引數,然後查詢並統計結果。上述執行先根據查詢條件查詢結果,然後統計了查詢資料庫fragment的baseSe結果記錄集合中記錄數。

15)查詢指定資料庫的集合當前可用的儲存空間

> use fragment
switched to db fragment
> db.baseSe.storageSize()
142564096

16)查詢指定資料庫的集合分配的儲存空間

> db.baseSe.totalSize()
144096000

上述查詢結果中,包括為集合(資料及其索引儲存)分配的儲存空間。

 

1.5安全管理

1)以安全認證模式啟動[[email protected] ~]# mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log使用--auth選項啟動mongod程序即可啟用認證模式。或者,也可以修改/etc/mongodb.conf,設定auth=true,重啟mongod程序。

2)新增使用者> db.createUser({user: "admin",pwd: "[email protected]#$qwer",roles: [ "readWrite", "dbAdmin" ]})新增資料庫使用者,新增成功,則顯示結果如下所示:

> db.createUser({user: "admin",pwd: "[email protected]#$qwer",roles: [ "readWrite", "dbAdmin" ]})
Successfully added user: { "user" : "admin", "roles" : [ "readWrite", "dbAdmin" ] }

3)安全認證前提是必須進入該使用者對應的database才行,出現1代表成功> db.auth("admin", "[email protected]#$qwer")資料庫安全認證。認證成功顯示結果:

> use admin
switched to db admin
> db.auth("admin", "[email protected]#$qwer")
1

如果是認證使用者,執行某些命令,可以看到正確執行結果,如下所示:

> db.system.users.find()  
{ "_id" : "fragment.admin", "user" : "admin", "db" : "fragment", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "/QZtFAvcavqZIm15FmbToA==", "storedKey" : "t91XZuIrnUYtuN1bG+hNg58R+w0=", "serverKey" : "vZLGW0nVpGSKfUHsS2RABOXhOb4=" } }, "roles" : [ { "role" : "readWrite", "db" : "fragment" }, { "role" : "dbAdmin", "db" : "fragment" } ] }

4、為資料庫寫資料(同步到磁碟)加鎖> db.runCommand({fsync:1,lock:1})說明:該操作已經對資料庫上鎖,不允許執行寫資料操作,一般在執行資料庫備份時有用。執行命令,結果示例如下:

> db.runCommand({fsync:1,lock:1})
{
	"info" : "now locked against writes, use db.fsyncUnlock() to unlock",
	"seeAlso" : "http://dochub.mongodb.org/core/fsynccommand",
	"ok" : 1
}

5)檢視當前鎖狀態> db.currentOp()說明:查詢結果如下所示:

> db.currentOp()
{
	"inprog" : [ ],
	"fsyncLock" : true,
	"info" : "use db.fsyncUnlock() to terminate the fsync write/snapshot lock"
}

其中,fsyncLock為1表示MongoDB的fsync程序(負責將寫入改變同步到磁碟)不允許其他程序執行寫資料操作

6)解鎖> use admin> db.$cmd.sys.unlock.findOne()說明:執行解鎖,結果如下所示:

> use admin
switched to db admin
> db.$cmd.sys.unlock.findOne()
{ "ok" : 1, "info" : "unlock completed" }

可以執行命令檢視鎖狀態:db.currentOp()狀態資訊如下:

> db.currentOp()
{ "inprog" : [ ] }

說明當前沒有鎖,可以執行寫資料操作。

1.6據備份、恢復與遷移管理

1)備份全部資料庫[[email protected] ~]# mkdir testbak[[email protected] ~]# cd testbak[[email protected] ~]# mongodump說明:預設備份目錄及資料檔案格式為./dump/[databasename]/[collectionname].bson

2)備份指定資料庫[[email protected] ~]# mongodump -d pagedb說明:備份資料庫pagedb中的資料。

3)備份一個數據庫中的某個集合[[email protected] ~]# mongodump -d pagedb -c page說明:備份資料庫pagedb的page集合。

4)恢復全部資料庫[[email protected] ~]# cd testbak[[email protected] ~]# mongorestore --drop說明:將備份的所有資料庫恢復到資料庫,--drop指定恢復資料之前刪除原來資料庫資料,否則會造成回覆後的資料中資料重複。

5)恢復某個資料庫的資料[[email protected] ~]# cd testbak[[email protected] ~]# mongorestore -d pagedb --drop說明:將備份的pagedb的資料恢復到資料庫。

6)恢復某個資料庫的某個集合的資料[[email protected] ~]# cd testbak[[email protected]6-vm01 ~]# mongorestore -d pagedb -c page --drop說明:將備份的pagedb的的page集合的資料恢復到資料庫。

7)向MongoDB匯入資料[[email protected] ~]# mongoimport -d pagedb -c page --type csv --headerline --drop < csvORtsvFile.csv說明:將檔案csvORtsvFile.csv的資料匯入到pagedb資料庫的page集合中,使用cvs或tsv檔案的列名作為集合的列名。

需要注意的是,使用--headerline選項時,只支援csv和tsv檔案。--type支援的型別有三個:csv、tsv、json其他各個選項的使用,可以檢視幫助:

[[email protected]-vm01 ~]# mongoimport --help  
Usage:
  mongoimport <options> <file>

Import CSV, TSV or JSON data into MongoDB. If no file is provided, mongoimport reads from stdin.

See http://docs.mongodb.org/manual/reference/program/mongoimport/ for more information.

general options:
      --help                     print usage
      --version                  print the tool version and exit

verbosity options:
  -v, --verbose                  more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)
      --quiet                    hide all log output

connection options:
  -h, --host=                    mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=                    server port (can also use --host hostname:port)

authentication options:
  -u, --username=                username for authentication
  -p, --password=                password for authentication
      --authenticationDatabase=  database that holds the user's credentials
      --authenticationMechanism= authentication mechanism to use

namespace options: