總所周知,MongoDB是一個NoSQL非數據庫系統,即一個數據庫能夠包含多個集合(Collection),每一個集合對應於關係數據庫中的表;而每一個集合中能夠存儲一組由列標識的記錄,列是能夠自由定義的,很是靈活,由一組列標識的實體的集合對應於關係數據庫表中的行。下面經過熟悉MongoDB的基本管理命令,來了解MongoDB提供的DBMS的基本功能和行爲。javascript
0)MongoDB的安裝html
[root@centos6-vm01 ~]# curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz [root@centos6-vm01 ~]# tar -zxvf mongodb-linux-x86_64-3.0.6.tgz [root@centos6-vm01 ~]# mv mongodb-linux-x86_64-3.0.6/ /usr/local/mongodb [root@centos6-vm01 ~]# vim /etc/profile ...... export PATH=$PATH:/usr/local/mongodb/bin/ [root@centos6-vm01 ~]# source /etc/profile 啓動mongodb [root@centos6-vm01 ~]# mkdir -p /data/db [root@centos6-vm01 ~]# cd /usr/local/mongodb/bin/ [root@centos6-vm01 bin]# ./mongod & [root@centos6-vm01 bin]# lsof -i:27017 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME mongod 24304 root 5u IPv4 187360 0t0 TCP *:27017 (LISTEN) mongod 24304 root 12u IPv4 187456 0t0 TCP localhost:27017->localhost:48742 (ESTABLISHED) mongo 24319 root 3u IPv4 187455 0t0 TCP localhost:48742->localhost:27017 (ESTABLISHED) ----------------------------------------------------- 鏈接mongodb報錯: Failed global initialization: BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly. 解決辦法: [root@centos6-vm01 ~]# vim /etc/profile ...... export LC_ALL=C [root@centos6-vm01 ~]# source /etc/profile -----------------------------------------------------
1)MongoDB命令幫助系統
在安裝MongoDB後,啓動服務器進程(mongod),能夠經過在客戶端命令mongo實現對MongoDB的管理和監控。看一下MongoDB的命令幫助系統:java
[root@centos6-vm01 ~]# mongo MongoDB shell version: 3.0.6 connecting to: test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: 2018-01-02T23:24:23.304+0000 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended. 2018-01-02T23:24:23.304+0000 I CONTROL [initandlisten] 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2018-01-02T23:24:23.307+0000 I CONTROL [initandlisten] > 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(),以下所示:linux
> db.help() DB methods: db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ] 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.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() 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()獲取到:mongodb
> 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]) 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]) db.mycoll.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } ) 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.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.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.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
有關數據庫和集合管理的相關命令,是最基礎和最經常使用的,如集合查詢、索引操做等。下面經過實際的例子來演示一些常見的命令:shell
1、基本命令
1)show dbs
顯示當前數據庫服務器上的數據庫數據庫
2)use pagedb
切換到指定數據庫pagedb的上下文,能夠在此上下文中管理pagedb數據庫以及其中的集合等json
3)show collections
顯示數據庫中全部的集合(collection)vim
4)db.serverStatus()
查看數據庫服務器的狀態。
有時,經過查看數據庫服務器的狀態,能夠判斷數據庫是否存在問題,若是有問題,如數據損壞,能夠及時執行修復。centos
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" ]
2、基本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
上述查詢結果中,包括爲集合(數據及其索引存儲)分配的存儲空間。
3、啓動與終止
1)正常啓動
[root@centos6-vm01 ~]# mongod --dbpath /data/db --logfile /var/mongo.log
說明:指定數據存儲目錄和日誌目錄
若是採用安全認證模式,須要加上--auth選項,如:
[root@centos6-vm01 ~]# mongod --auth --dbpath /data/db --logfile /var/mongo.log
2)以修復模式啓動
[root@centos6-vm01 ~]# mongod --repair
以修復模式啓動數據庫。
實際極可能數據庫數據損壞或數據狀態不一致,致使沒法正常啓動MongoDB服務器,根據啓動信息能夠看到須要進行修復。或者執行:
[root@centos6-vm01 ~]# mongod -f /etc/mongodb.conf --repair
3)終止服務器進程
> db.shutdownServer()
終止數據庫服務器進程。或者,能夠直接kill掉mongod進程便可。
4、安全管理
1)以安全認證模式啓動
[root@centos6-vm01 ~]# mongod --auth --dbpath /usr/mongo/data --logfile /var/mongo.log
使用--auth選項啓動mongod進程便可啓用認證模式。
或者,也能夠修改/etc/mongodb.conf,設置auth=true,重啓mongod進程。
2)添加用戶
> db.createUser({user: "admin",pwd: "1234!@#$qwer",roles: [ "readWrite", "dbAdmin" ]})
添加數據庫用戶,添加成功,則顯示結果以下所示:
> db.createUser({user: "admin",pwd: "1234!@#$qwer",roles: [ "readWrite", "dbAdmin" ]}) Successfully added user: { "user" : "admin", "roles" : [ "readWrite", "dbAdmin" ] }
3)安全認證
前提是必須進入該用戶對應的database才行,出現1表明成功
> db.auth("admin", "1234!@#$qwer")
數據庫安全認證。認證成功顯示結果:
> use admin switched to db admin > db.auth("admin", "1234!@#$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" } ] }
四、爲數據庫寫數據(同步到磁盤)加鎖
> 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" : [ ] }
說明當前沒有鎖,能夠執行寫數據操做。
5、據備份、恢復與遷移管理
1)備份所有數據庫
[root@centos6-vm01 ~]# mkdir testbak
[root@centos6-vm01 ~]# cd testbak
[root@centos6-vm01 ~]# mongodump
說明:默認備份目錄及數據文件格式爲./dump/[databasename]/[collectionname].bson
2)備份指定數據庫
[root@centos6-vm01 ~]# mongodump -d pagedb
說明:備份數據庫pagedb中的數據。
3)備份一個數據庫中的某個集合
[root@centos6-vm01 ~]# mongodump -d pagedb -c page
說明:備份數據庫pagedb的page集合。
4)恢復所有數據庫
[root@centos6-vm01 ~]# cd testbak
[root@centos6-vm01 ~]# mongorestore --drop
說明:將備份的全部數據庫恢復到數據庫,--drop指定恢復數據以前刪除原來數據庫數據,不然會形成回覆後的數據中數據重複。
5)恢復某個數據庫的數據
[root@centos6-vm01 ~]# cd testbak
[root@centos6-vm01 ~]# mongorestore -d pagedb --drop
說明:將備份的pagedb的數據恢復到數據庫。
6)恢復某個數據庫的某個集合的數據
[root@centos6-vm01 ~]# cd testbak
[root@centos6-vm01 ~]# mongorestore -d pagedb -c page --drop
說明:將備份的pagedb的的page集合的數據恢復到數據庫。
7)向MongoDB導入數據
[root@centos6-vm01 ~]# mongoimport -d pagedb -c page --type csv --headerline --drop < csvORtsvFile.csv
說明:將文件csvORtsvFile.csv的數據導入到pagedb數據庫的page集合中,使用cvs或tsv文件的列名做爲集合的列名。
須要注意的是,使用--headerline選項時,只支持csv和tsv文件。
--type支持的類型有三個:csv、tsv、json
其餘各個選項的使用,能夠查看幫助:
[root@centos6-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: -d, --db= database to use -c, --collection= collection to use input options: -f, --fields= comma separated list of field names, e.g. -f name,age --fieldFile= file with field names - 1 per line --file= file to import from; if not specified, stdin is used --headerline use first line in input source as the field list (CSV and TSV only) --jsonArray treat input source as a JSON array --type= input format to import: json, csv, or tsv (defaults to 'json') ingest options: --drop drop collection before inserting documents --ignoreBlanks ignore fields with empty values in CSV and TSV --maintainInsertionOrder insert documents in the order of their appearance in the input source -j, --numInsertionWorkers= number of insert operations to run concurrently (defaults to 1) --stopOnError stop importing at first insert/upsert error --upsert insert or update objects that already exist --upsertFields= comma-separated fields for the query part of the upsert --writeConcern= write concern options e.g. --writeConcern majority, --writeConcern '{w: 3, wtimeout: 500, fsync: true, j: true}' (defaults to 'majority')
8)從向MongoDB導出數據
[root@centos6-vm01 ~]# 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 指定查詢條件
其餘各個選項的使用,能夠查看幫助:
[root@centos6-vm01 ~]# mongoexport --help Usage: mongoexport <options> Export data from MongoDB in CSV or JSON format. See http://docs.mongodb.org/manual/reference/program/mongoexport/ 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: -d, --db= database to use -c, --collection= collection to use output options: -f, --fields= comma separated list of field names (required for exporting CSV) e.g. -f "name,age" --fieldFile= file with field names - 1 per line --type= the output format, either json or csv (defaults to 'json') -o, --out= output file; if not specified, stdout is used --jsonArray output to a JSON array rather than one object per line --pretty output JSON formatted to be human-readable querying options: -q, --query= query filter, as a JSON string, e.g., '{x:{$gt:1}}' -k, --slaveOk allow secondary reads if available (default true) --forceTableScan force a table scan (do not use $snapshot) --skip= number of documents to skip --limit= limit the number of documents to export --sort= sort order, as a JSON string, e.g. '{x:1}'
注意:若是上面的選項-q指定一個查詢條件,須要使用單引號括起來,以下所示:
[root@centos6-vm01 ~]# mongoexport -d page -c Article -q '{"spiderName": "mafengwoSpider"}' -f _id,title,content,images,publishDate,spiderName,url --jsonArray > mafengwoArticle.txt 2018-01-03T08:12:41.234+0800 connected to: localhost 2018-01-03T08:12:41.234+0800 exported 0 records [root@centos6-vm01 ~]# ll mafengwoArticle.txt -rw-r--r--. 1 root root 3 Jan 3 00:12 mafengwoArticle.txt
不然,就會出現下面的錯誤:
ERROR: too many positional options
6、遠程鏈接管理
1)基於mongo實現遠程鏈接
[root@centos6-vm01 ~]# mongo 192.168.10.220:27017/pagedb
或者
[root@centos6-vm01 ~]# mongo 192.168.10.220:27017/pagedb -ukevin -p123456kevin
經過mongo實現鏈接,能夠很是靈活的選擇參數選項,參看命令幫助,以下所示:
[root@centos6-vm01 ~]# mongo --help MongoDB shell version: 3.0.6 usage: mongo [options] [db address] [file names (ending in .js)] db address can be: foo foo database on local machine 192.169.0.5/foo foo database on 192.168.0.5 machine 192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999 Options: --shell run the shell after executing files --nodb don't connect to mongod on startup - no 'db address' arg expected --norc will not run the ".mongorc.js" file on start up --quiet be less chatty --port arg port to connect to --host arg server to connect to --eval arg evaluate javascript -h [ --help ] show this usage information --version show version information --verbose increase verbosity --ipv6 enable IPv6 support (disabled by default) Authentication Options: -u [ --username ] arg username for authentication -p [ --password ] arg password for authentication --authenticationDatabase arg user source (defaults to dbname) --authenticationMechanism arg authentication mechanism --gssapiServiceName arg (=mongodb) Service name to use when authenticating using GSSAPI/Kerberos --gssapiHostName arg Remote host name to use for purpose of GSSAPI/Kerberos authentication file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified
2)基於MongoDB支持的javascript實現遠程鏈接
當你已經鏈接到一個遠程的MongoDB數據庫服務器(例如,經過mongo鏈接到192.168.0.184),如今想要在這個會話中鏈接另外一個遠程的數據庫服務器(192.168.0.197),能夠執行以下命令:
> var x = new Mongo('192.168.10.220:27017') > var ydb = x.getDB('pagedb'); > use ydb switched to db ydb > db ydb > ydb.page.findOne() { "_id" : ObjectId("4eded6a5bf3bfa0014000003"), "content" : "巴黎是浪漫的城市,但是...", "pubdate" : "2006-03-19", "title" : "巴黎:從布魯塞爾趕到巴黎", "url" : "http://france.bytravel.cn/Scenery/528/cblsegdbl.html" }
> var x = new Mongo('192.168.0.197:27017') > var ydb = x.getDB('pagedb', 'shirdrn', '(jkfFS$343$_\=\,.F@3'); > use ydb switched to db ydb
==========================擴展知識==========================
節點角色
MongoDB讀寫分離
MongoDB副本集對讀寫分離的支持是經過Read Preferences特性進行支持的,這個特性很是複雜和靈活。設置讀寫分離須要先在從節點SECONDARY設置setSlaveOk。應用程序驅動經過read reference來設定如何對副本集進行讀取操做,默認的,客戶端驅動全部的讀操做都是直接訪問primary節點的,從而保證了數據的嚴格一致性。有以下幾種模式:
mongo shell中複製相關方法
複製數據庫的命令
用戶管理和認證方法
官方詳細檔:https://docs.mongodb.com/master/reference/security/#security-methods-in-the-mongo-shell
角色管理方法
官方詳細檔:https://docs.mongodb.com/master/reference/security/#security-methods-in-the-mongo-shell