MongoDB基本管理命令


這篇MongoDB基本管理命令比較全面,轉載保留,原文

目錄

  1. MongoDB命令幫助系統
  2. 基本命令及實例
    1. 一基本命令
    2. 二基本DDL和DML
    3. 三啟動與終止
    4. 四安全管理
    5. 五數據備份恢復與遷移管理
    6. 六遠程連接管理

MongoDB是一個NoSQL數據庫系統:一個數據庫可以包含多個集合(Collection),每個集合對應於關系數據庫中的表;而每個集合中可以存儲一組由列標識的記錄,列是可以自由定義的,非常靈活,由一組列標識的實體的集合對應於關系數據庫表中的行。下面通過熟悉MongoDB的基本管理命令,來了解MongoDB提供的DBMS的基本功能和行為。 

MongoDB命令幫助系統 

在安裝MongoDB后,啟動服務器進程(mongod),可以通過在客戶端命令mongo實現對MongoDB的管理和監控。看一下MongoDB的命令幫助系統:

 1 root@dev2:~# mongo
 2 MongoDB shell version: 1.8.3
 3 connecting to: test
 4 > help
 5         db.help()                    help on db methods
 6         db.mycoll.help()             help on collection methods
 7         rs.help()                    help on replica set methods
 8         help connect                 connecting to a db help
 9         help admin                   administrative help
10         help misc                    misc things to know
11         help mr                      mapreduce help
12 
13         show dbs                     show database names
14         show collections             show collections in current database
15         show users                   show users in current database
16         show profile                 show most recent system.profile entries with time >= 1ms
17         use <db_name>                set current database
18         db.foo.find()                list objects in collection foo
19         db.foo.find( { a : 1 } )     list objects in foo where a == 1
20         it                           result of the last line evaluated; use to further iterate
21         DBQuery.shellBatchSize = x   set default number of items to display on shell
22         exit                         quit the mongo shell

這是MongoDB最頂層的命令列表,主要告訴我們管理數據庫相關的一些抽象的范疇:數據庫操作幫助、集合操作幫助、管理幫助。如果你想了解數據庫操作更詳細的幫助命令,可以直接使用db.help(),如下所示:

 1 > db.help()
 2 DB methods:
 3         db.addUser(username, password[, readOnly=false])
 4         db.auth(username, password)
 5         db.cloneDatabase(fromhost)
 6         db.commandHelp(name) returns the help for the command
 7         db.copyDatabase(fromdb, todb, fromhost)
 8         db.createCollection(name, { size : ..., capped : ..., max : ... } )
 9         db.currentOp() displays the current operation in the db
10         db.dropDatabase()
11         db.eval(func, args) run code server-side
12         db.getCollection(cname) same as db['cname'] or db.cname
13         db.getCollectionNames()
14         db.getLastError() - just returns the err msg string
15         db.getLastErrorObj() - return full status object
16         db.getMongo() get the server connection object
17         db.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pair
18         db.getName()
19         db.getPrevError()
20         db.getProfilingLevel() - deprecated
21         db.getProfilingStatus() - returns if profiling is on and slow threshold 
22         db.getReplicationInfo()
23         db.getSiblingDB(name) get the db at the same server as this one
24         db.isMaster() check replica primary status
25         db.killOp(opid) kills the current operation in the db
26         db.listCommands() lists all the db commands
27         db.printCollectionStats()
28         db.printReplicationInfo()
29         db.printSlaveReplicationInfo()
30         db.printShardingStatus()
31         db.removeUser(username)
32         db.repairDatabase()
33         db.resetError()
34         db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }
35         db.serverStatus()
36         db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all
37         db.shutdownServer()
38         db.stats()
39         db.version() current version of the server
40         db.getMongo().setSlaveOk() allow queries on a replication slave server

對數據庫進行管理和操作的基本命令,可以從上面獲取到。如果想要得到更多,而且每個命令的詳細用法,可以使用上面列出的db.listCommands()查詢。

 

另一個比較基礎的是對指定數據庫的集合進行操作、管理和監控,可以通過查詢db.mycoll.help()獲取到:

 1 > db.mycoll.help()
 2 DBCollection help
 3         db.mycoll.find().help() - show DBCursor help
 4         db.mycoll.count()
 5         db.mycoll.dataSize()
 6         db.mycoll.distinct( key ) - eg. db.mycoll.distinct( 'x' )
 7         db.mycoll.drop() drop the collection
 8         db.mycoll.dropIndex(name)
 9         db.mycoll.dropIndexes()
10         db.mycoll.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
11         db.mycoll.reIndex()
12         db.mycoll.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
13                                                       e.g. db.mycoll.find( {x:77} , {name:1, x:1} )
14         db.mycoll.find(...).count()
15         db.mycoll.find(...).limit(n)
16         db.mycoll.find(...).skip(n)
17         db.mycoll.find(...).sort(...)
18         db.mycoll.findOne([query])
19         db.mycoll.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
20         db.mycoll.getDB() get DB object associated with collection
21         db.mycoll.getIndexes()
22         db.mycoll.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
23         db.mycoll.mapReduce( mapFunction , reduceFunction , <optional params> )
24         db.mycoll.remove(query)
25         db.mycoll.renameCollection( newName , <dropTarget> ) renames the collection.
26         db.mycoll.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
27         db.mycoll.save(obj)
28         db.mycoll.stats()
29         db.mycoll.storageSize() - includes free space allocated to this collection
30         db.mycoll.totalIndexSize() - size in bytes of all the indexes
31         db.mycoll.totalSize() - storage allocated for all data and indexes
32         db.mycoll.update(query, object[, upsert_bool, multi_bool])
33         db.mycoll.validate() - SLOW
34         db.mycoll.getShardVersion() - only for use with sharding

有關數據庫和集合管理的相關命令,是最基礎和最常用的,如集合查詢、索引操作等。

 

基本命令及實例 

下面通過實際的例子來演示一些常見的命令:

(一)基本命令 

1、show dbs

顯示當前數據庫服務器上的數據庫
2、use pagedb
 切換到指定數據庫pagedb的上下文,可以在此上下文中管理pagedb數據庫以及其中的集合等
3、show collections
顯示數據庫中所有的集合(collection)
4、db.serverStatus()  
查看數據庫服務器的狀態。示例如下所示:
 1 {
 2         "host" : "dev2",
 3         "version" : "1.8.3",
 4         "process" : "mongod",
 5         "uptime" : 845446,
 6         "uptimeEstimate" : 839192,
 7         "localTime" : ISODate("2011-12-27T04:03:12.512Z"),
 8         "globalLock" : {
 9                 "totalTime" : 845445636925,
10                 "lockTime" : 13630973982,
11                 "ratio" : 0.016122827283818857,
12                 "currentQueue" : {
13                         "total" : 0,
14                         "readers" : 0,
15                         "writers" : 0
16                 },
17                 "activeClients" : {
18                         "total" : 0,
19                         "readers" : 0,
20                         "writers" : 0
21                 }
22         },
23         "mem" : {
24                 "bits" : 64,
25                 "resident" : 12208,
26                 "virtual" : 466785,
27                 "supported" : true,
28                 "mapped" : 466139
29         },
30         "connections" : {
31                 "current" : 27,
32                 "available" : 792
33         },
34         "extra_info" : {
35                 "note" : "fields vary by platform",
36                 "heap_usage_bytes" : 70895216,
37                 "page_faults" : 17213898
38         },
39         "indexCounters" : {
40                 "btree" : {
41                         "accesses" : 4466653,
42                         "hits" : 4465526,
43                         "misses" : 1127,
44                         "resets" : 0,
45                         "missRatio" : 0.00025231420484197006
46                 }
47         },
48         "backgroundFlushing" : {
49                 "flushes" : 14090,
50                 "total_ms" : 15204393,
51                 "average_ms" : 1079.0910574875797,
52                 "last_ms" : 669,
53                 "last_finished" : ISODate("2011-12-27T04:02:28.713Z")
54         },
55         "cursors" : {
56                 "totalOpen" : 3,
57                 "clientCursors_size" : 3,
58                 "timedOut" : 53
59         },
60         "network" : {
61                 "bytesIn" : 63460818650,
62                 "bytesOut" : 763926196104,
63                 "numRequests" : 67055921
64         },
65         "opcounters" : {
66                 "insert" : 7947057,
67                 "query" : 35720451,
68                 "update" : 16263239,
69                 "delete" : 154,
70                 "getmore" : 91707,
71                 "command" : 68520
72         },
73         "asserts" : {
74                 "regular" : 0,
75                 "warning" : 1,
76                 "msg" : 0,
77                 "user" : 7063866,
78                 "rollovers" : 0
79         },
80         "writeBacksQueued" : false,
81         "ok" : 1
82 }

有時,通過查看數據庫服務器的狀態,可以判斷數據庫是否存在問題,如果有問題,如數據損壞,可以及時執行修復。

5、查詢指定數據庫統計信息
use fragment
db.stats()
查詢結果示例如下所示:
 1 > db.stats()
 2 {
 3 &nbsp; &nbsp; &nbsp; &nbsp; "db" : "fragment",
 4 &nbsp; &nbsp; &nbsp; &nbsp; "collections" : 12,
 5 &nbsp; &nbsp; &nbsp; &nbsp; "objects" : 384553,
 6 &nbsp; &nbsp; &nbsp; &nbsp; "avgObjSize" : 3028.40198360174,
 7 &nbsp; &nbsp; &nbsp; &nbsp; "dataSize" : 1164581068,
 8 &nbsp; &nbsp; &nbsp; &nbsp; "storageSize" : 1328351744,
 9 &nbsp; &nbsp; &nbsp; &nbsp; "numExtents" : 109,
10 &nbsp; &nbsp; &nbsp; &nbsp; "indexes" : 10,
11 &nbsp; &nbsp; &nbsp; &nbsp; "indexSize" : 16072704,
12 &nbsp; &nbsp; &nbsp; &nbsp; "fileSize" : 4226809856,
13 &nbsp; &nbsp; &nbsp; &nbsp; "ok" : 1
14 }

顯示fragment數據庫的統計信息。

6、查詢指定數據庫包含的集合名稱列表
db.getCollectionNames()
結果如下所示:
 
 1 > db.getCollectionNames()
 2 [
 3         "17u",
 4         "baseSe",
 5         "bytravel",
 6         "daodao",
 7         "go2eu",
 8         "lotour",
 9         "lvping",
10         "mafengwo",
11         "sina",
12         "sohu",
13         "system.indexes"
14 ]

(二)基本DDL和DML

 1、創建數據庫

如果你習慣了關系型數據庫,你可能會尋找相關的創建數據庫的命令。在MongoDB中,你可以直接通過use dbname來切換到這個數據庫上下文下面,系統會自動延遲創建該數據庫,例如:
 
 1 > show dbs
 2 admin   0.03125GB
 3 local   (empty)
 4 pagedb  0.03125GB
 5 test    0.03125GB
 6 > use LuceneIndexDB
 7 switched to db LuceneIndexDB
 8 > show dbs
 9 admin   0.03125GB
10 local   (empty)
11 pagedb  0.03125GB
12 test    0.03125GB
13 > db
14 LuceneIndexDB
15 > db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})
16 > show dbs
17 LuceneIndexDB   0.03125GB
18 admin   0.03125GB
19 local   (empty)
20 pagedb  0.03125GB
21 test    0.03125GB
22 >

可見,在use指定數據庫后,並且向指定其中的一個集合並插入數據后,數據庫和集合都被創建了。

2、刪除數據庫
直接使用db.dropDatabase()即可刪除數據庫。
3、創建集合
可以使用命令db.createCollection(name, { size : ..., capped : ..., max : ... } )創建集合,示例如下所示:
 
1 > db.createCollection('replicationColletion', {'capped':true, 'size':10240, 'max':17855200})
2 { "ok" : 1 }
3 > show collections
4 replicationColletion
5 storeCollection
6 system.indexes 

4、刪除集合

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

5、插入更新記錄

直接使用集合的save方法,如下所示:

1 > <em>db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})</em>

 

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

6、查詢一條記錄

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

1 > db.storeCollection.findOne({'version':'3.5'})
2 {
3         "_id" : ObjectId("4ef970f23c1fc4613425accc"),
4         "version" : "3.5",
5         "segment" : "e3ol6"
6 }


7、查詢多條記錄 

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

8、刪除記錄

使用集合的remove()方法,參數指定為查詢條件,示例如下所示:

1 > db.storeCollection.remove({'version':'3.5'})
2 > db.storeCollection.findOne()
3 null

9、創建索引

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

1 > use pagedb
2 switched to db pagedb
3 > db.page.ensureIndex({'title':1, 'url':-1})
4 > db.system.indexes.find()
5 { "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : 1 }, "v" : 0 }
6 { "name" : "_id_", "ns" : "pagedb.system.users", "key" : { "_id" : 1 }, "v" : 0}
7 { "_id" : ObjectId("4ef977633c1fc4613425accd"), "ns" : "pagedb.page", "key" : {"title" : 1, "url" : -1 }, "name" : "title_1_url_-1", "v" : 0 }

 上述,ensureIndex方法參數中,數字1表示升序,-1表示降序。

 

使用db.system.indexes.find()可以查詢全部索引。

10、查詢索引

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

 1 > db.page.getIndexes()
 2 [
 3         {
 4                 "name" : "_id_",
 5                 "ns" : "pagedb.page",
 6                 "key" : {
 7                         "_id" : 1
 8                 },
 9                 "v" : 0
10         },
11         {
12                 "_id" : ObjectId("4ef977633c1fc4613425accd"),
13                 "ns" : "pagedb.page",
14                 "key" : {
15                         "title" : 1,
16                         "url" : -1
17                 },
18                 "name" : "title_1_url_-1",
19                 "v" : 0
20         }
21 ]

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

11、刪除索引

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

1         db.mycoll.dropIndex(name)
2         db.mycoll.dropIndexes()

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

 

12、索引重建

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

 1 > db.page.reIndex()
 2 {
 3         "nIndexesWas" : 2,
 4         "msg" : "indexes dropped for collection",
 5         "ok" : 1,
 6         "nIndexes" : 2,
 7         "indexes" : [
 8                 {
 9                         "name" : "_id_",
10                         "ns" : "pagedb.page",
11                         "key" : {
12                                 "_id" : 1
13                         },
14                         "v" : 0
15                 },
16                 {
17                         "_id" : ObjectId("4ef977633c1fc4613425accd"),
18                         "ns" : "pagedb.page",
19                         "key" : {
20                                 "title" : 1,
21                                 "url" : -1
22                         },
23                         "name" : "title_1_url_-1",
24                         "v" : 0
25                 }
26         ],
27         "ok" : 1
28 }

 13、統計集合記錄數

use fragment

db.baseSe.count()
統計結果,如下所示: 

1 > use fragment
2 switched to db fragment
3 > db.baseSe.count()
4 36749

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

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

 use fragment

db.baseSe.find().count()

find()可以提供查詢參數,然后查詢並統計結果,如下所示: 

1 > use fragment
2 switched to db fragment
3 > db.baseSe.find().count()
4 36749

上述執行先根據查詢條件查詢結果,然后統計了查詢數據庫fragment的baseSe結果記錄集合中記錄數。

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+\/")
添加數據庫用戶,添加成功,則顯示結果如下所示:
1 {
2         "user" : "admin",
3         "readOnly" : false,
4         "pwd" : "995d2143e0bf79cba24b58b3e41852cd"
5 }

3、安全認證

db.auth("admin", ",%F23_kj~00Opoo0+\/")
數據庫安全認證。認證成功顯示結果:
1 {
2         "user" : "admin",
3         "readOnly" : false,
4         "pwd" : "995d2143e0bf79cba24b58b3e41852cd"
5 }

  

如果是認證用戶,執行某些命令,可以看到正確執行結果,如下所示:
1 db.system.users.find()
2 { "_id" : ObjectId("4ef940a13c1fc4613425acc8"), "user" : "admin", "readOnly" : false, "pwd" : "995d2143e0bf79cba24b58b3e41852cd" }

否則,認證失敗,則執行相關命令會提示錯誤:

1 db.system.users.find()
2 error: {
3         "$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1", "code" : 10057
4 }

 

4、為數據庫寫數據(同步到磁盤)加鎖
db.runCommand({fsync:1,lock:1})
說明:
該操作已經對數據庫上鎖,不允許執行寫數據操作,一般在執行數據庫備份時有用。執行命令,結果示例如下:
1 {
2         "info" : "now locked against writes, use db.$cmd.sys.unlock.findOne() to unlock",
3         "ok" : 1
4 }

 

5、查看當前鎖狀態
db.currentOp()
說明:
查詢結果如下所示:
1 {
2         "inprog" : [ ],
3         "fsyncLock" : 1,
4         "info" : "use db.$cmd.sys.unlock.findOne() to terminate the fsync write/snapshot lock"
5 }

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

6、解鎖
use admin
db.$cmd.sys.unlock.findOne()
說明:
執行解鎖,結果如下所示:
1 { "ok" : 1, "info" : "unlock requested" }

可以執行命令查看鎖狀態:

db.currentOp()
狀態信息如下:
1 { "inprog" : [ ] }

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

 

(五)數據備份、恢復與遷移管理 

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
其他各個選項的使用,可以查看幫助:
 1 mongoimport --help
 2 options:
 3   --help                  produce help message
 4   -v [ --verbose ]        be more verbose (include multiple times for more
 5                           verbosity e.g. -vvvvv)
 6   -h [ --host ] arg       mongo host to connect to ( <set name>/s1,s2 for sets)
 7   --port arg              server port. Can also use --host hostname:port
 8   --ipv6                  enable IPv6 support (disabled by default)
 9   -u [ --username ] arg   username
10   -p [ --password ] arg   password
11   --dbpath arg            directly access mongod database files in the given
12                           path, instead of connecting to a mongod  server -
13                           needs to lock the data directory, so cannot be used
14                           if a mongod is currently accessing the same path
15   --directoryperdb        if dbpath specified, each db is in a separate
16                           directory
17   -d [ --db ] arg         database to use
18   -c [ --collection ] arg collection to use (some commands)
19   -f [ --fields ] arg     comma separated list of field names e.g. -f name,age
20   --fieldFile arg         file with fields names - 1 per line
21   --ignoreBlanks          if given, empty fields in csv and tsv will be ignored
22   --type arg              type of file to import.  default: json (json,csv,tsv)
23   --file arg              file to import from; if not specified stdin is used
24   --drop                  drop collection first
25   --headerline            CSV,TSV only - use first line as headers
26   --upsert                insert or update objects that already exist
27   --upsertFields arg      comma-separated fields for the query part of the
28                           upsert. You should make sure this is indexed
29   --stopOnError           stop importing at first error rather than continuing
30   --jsonArray             load a json array, not one item per line. Currently
31                           limited to 4MB.

8、從向MongoDB導出數據

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 指定查詢條件
其他各個選項的使用,可以查看幫助:
 1 mongoexport --help
 2 options:
 3   --help                  produce help message
 4   -v [ --verbose ]        be more verbose (include multiple times for more verbosity e.g. -vvvvv)
 5   -h [ --host ] arg       mongo host to connect to ( <set name>/s1,s2 for sets)
 6   --port arg              server port. Can also use --host hostname:port
 7   --ipv6                  enable IPv6 support (disabled by default)
 8   -u [ --username ] arg   username
 9   -p [ --password ] arg   password
10   --dbpath arg            directly access mongod database files in the given
11                           path, instead of connecting to a mongod  server -
12                           needs to lock the data directory, so cannot be used
13                           if a mongod is currently accessing the same path
14   --directoryperdb        if dbpath specified, each db is in a separate directory
15   -d [ --db ] arg         database to use
16   -c [ --collection ] arg collection to use (some commands)
17   -f [ --fields ] arg     comma separated list of field names e.g. -f name,age
18   --fieldFile arg         file with fields names - 1 per line
19   -q [ --query ] arg      query filter, as a JSON string
20   --csv                   export to csv instead of json
21   -o [ --out ] arg        output file; if not specified, stdout is used
22   --jsonArray             output to a json array rather than one object per line

注意:

如果上面的選項-q指定一個查詢條件,需要使用單引號括起來,如下所示:
1 mongoexport -d page -c Article -q '{"spiderName": "mafengwoSpider"}' -f _id,title,content,images,publishDate,spiderName,url --jsonArray > mafengwoArticle.txt

 

否則,就會出現下面的錯誤:
1 ERROR: too many positional options

 (六)遠程連接管理 

1、基於mongo實現遠程連接
1 mongo -u admin -p admin 192.168.0.197:27017/pagedb

通過mongo實現連接,可以非常靈活的選擇參數選項,參看命令幫助,如下所示:

 1 mongo --help
 2 MongoDB shell version: 1.8.3
 3 usage: mongo [options] [db address] [file names (ending in .js)]
 4 db address can be:
 5   foo                   foo database on local machine
 6   192.169.0.5/foo       foo database on 192.168.0.5 machine
 7   192.169.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
 8 options:
 9   --shell               run the shell after executing files
10   --nodb                don't connect to mongod on startup - no 'db address' 
11                         arg expected
12   --quiet               be less chatty
13   --port arg            port to connect to
14   --host arg            server to connect to
15   --eval arg            evaluate javascript
16   -u [ --username ] arg username for authentication
17   -p [ --password ] arg password for authentication
18   -h [ --help ]         show this usage information
19   --version             show version information
20   --verbose             increase verbosity
21   --ipv6                enable IPv6 support (disabled by default)

 2、基於MongoDB支持的javascript實現遠程連接

當你已經連接到一個遠程的MongoDB數據庫服務器(例如,通過mongo連接到192.168.0.184),現在想要在這個會話中連接另一個遠程的數據庫服務器(192.168.0.197),可以執行如下命令:
 1 > var x = new Mongo('192.168.0.197:27017')
 2 > var ydb = x.getDB('pagedb');
 3 > use ydb
 4 switched to db ydb
 5 > db
 6 ydb
 7 > ydb.page.findOne()
 8 {
 9         "_id" : ObjectId("4eded6a5bf3bfa0014000003"),
10         "content" : "巴黎是浪漫的城市,可是...",
11         "pubdate" : "2006-03-19",
12         "title" : "巴黎:從布魯塞爾趕到巴黎",
13         "url" : "http://france.bytravel.cn/Scenery/528/cblsegdbl.html"
14 }

上述通過MongoDB提供的JavaScript腳本,實現對另一個遠程數據庫服務器進行連接,操作指定數據庫pagedb的page集合。

如果啟用了安全認證模式,可以在獲取數據庫連接實例時,指定認證賬號,例如:
1 > var x = new Mongo('192.168.0.197:27017')
2 > var ydb = x.getDB('pagedb', 'shirdrn', '(jkfFS$343$_\=\,.F@3');
3 > use ydb
4 switched to db ydb

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM