mongodb基本コマンド使用概要


詳細
         MongoDBはNoSQLデータベースシステムです.1つのデータベースに複数のコレクション(Collection)を含めることができ、各コレクションはリレーショナル・データベースのテーブルに対応します.各セットには、カラムによって識別されるレコードのセットを格納できます.カラムは自由に定義でき、非常に柔軟で、カラムによって識別されるエンティティのセットは、リレーショナル・データベース・テーブルのローに対応します.以下、MongoDBの基本管理コマンドを熟知することで、MongoDBが提供するDBMSの基本機能と動作を理解します.
         参照:http://blog.csdn.net/shirdrn/article/details/7105539
 
         一、MongoDBコマンドヘルプシステム
             MongoDBをインストールした後、サーバープロセス(mongod)を起動し、クライアントコマンドmongoでMongoDBの管理と監視を実現します.MongoDBのコマンドヘルプシステムを見てみましょう.             
dengqs@mongodbServer:~# ./mongo  
MongoDB shell version: 1.8.3  
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 >= 1ms  
        use                 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.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 : 1 }  
        db.serverStatus()  
        db.setProfilingLevel(level,) 0=off 1=slow 2=all  
        db.shutdownServer()  
        db.stats()  
        db.version() current version of the server  
        db.getMongo().setSlaveOk() allow queries on a replication slave server 

             データベースの管理と操作の基本コマンドは、上から取得できます.より多く、各コマンドの詳細な使用方法を取得するには、上記のdb.listCommands()クエリーを使用します.
             もう1つの比較の基礎は、db.mycol.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: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.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" : "dev2",  
        "version" : "1.8.3",  
        "process" : "mongod",  
        "uptime" : 845446,  
        "uptimeEstimate" : 839192,  
        "localTime" : ISODate("2011-12-27T04:03:12.512Z"),  
        "globalLock" : {  
                "totalTime" : 845445636925,  
                "lockTime" : 13630973982,  
                "ratio" : 0.016122827283818857,  
                "currentQueue" : {  
                        "total" : 0,  
                        "readers" : 0,  
                        "writers" : 0  
                },  
                "activeClients" : {  
                        "total" : 0,  
                        "readers" : 0,  
                        "writers" : 0  
                }  
        },  
        "mem" : {  
                "bits" : 64,  
                "resident" : 12208,  
                "virtual" : 466785,  
                "supported" : true,  
                "mapped" : 466139  
        },  
        "connections" : {  
                "current" : 27,  
                "available" : 792  
        },  
        "extra_info" : {  
                "note" : "fields vary by platform",  
                "heap_usage_bytes" : 70895216,  
                "page_faults" : 17213898  
        },  
        "indexCounters" : {  
                "btree" : {  
                        "accesses" : 4466653,  
                        "hits" : 4465526,  
                        "misses" : 1127,  
                        "resets" : 0,  
                        "missRatio" : 0.00025231420484197006  
                }  
        },  
        "backgroundFlushing" : {  
                "flushes" : 14090,  
                "total_ms" : 15204393,  
                "average_ms" : 1079.0910574875797,  
                "last_ms" : 669,  
                "last_finished" : ISODate("2011-12-27T04:02:28.713Z")  
        },  
        "cursors" : {  
                "totalOpen" : 3,  
                "clientCursors_size" : 3,  
                "timedOut" : 53  
        },  
        "network" : {  
                "bytesIn" : 63460818650,  
                "bytesOut" : 763926196104,  
                "numRequests" : 67055921  
        },  
        "opcounters" : {  
                "insert" : 7947057,  
                "query" : 35720451,  
                "update" : 16263239,  
                "delete" : 154,  
                "getmore" : 91707,  
                "command" : 68520  
        },  
        "asserts" : {  
                "regular" : 0,  
                "warning" : 1,  
                "msg" : 0,  
                "user" : 7063866,  
                "rollovers" : 0  
        },  
        "writeBacksQueued" : false,  
        "ok" : 1  
}  
  ,             ,             ,     ,     ,        。
5、           
use fragment
db.stats()
          :
> db.stats()  
{  
        "db" : "fragment",  
        "collections" : 12,  
        "objects" : 384553,  
        "avgObjSize" : 3028.40198360174,  
        "dataSize" : 1164581068,  
        "storageSize" : 1328351744,  
        "numExtents" : 109,  
        "indexes" : 10,  
        "indexSize" : 16072704,  
        "fileSize" : 4226809856,  
        "ok" : 1  
}  
  fragment        。
6、                
db.getCollectionNames()
      :
> db.getCollectionNames()  
[  
        "17u",  
        "baseSe",  
        "bytravel",  
        "daodao",  
        "go2eu",  
        "lotour",  
        "lvping",  
        "mafengwo",  
        "sina",  
        "sohu",  
        "system.indexes"  
] 

 
         三、基本DDLとDML
1、     
            ,                 。 MongoDB ,       use dbname              ,             ,  :
> show dbs  
admin   0.03125GB  
local   (empty)  
pagedb  0.03125GB  
test    0.03125GB  
> use LuceneIndexDB  
switched to db LuceneIndexDB  
> show dbs  
admin   0.03125GB  
local   (empty)  
pagedb  0.03125GB  
test    0.03125GB  
> db  
LuceneIndexDB  
> db.storeCollection.save({'version':'3.5', 'segment':'e3ol6'})  
> show dbs  
LuceneIndexDB   0.03125GB  
admin   0.03125GB  
local   (empty)  
pagedb  0.03125GB  
test    0.03125GB  
>  
  , 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'})  
    ,  save                  。
6、      
  findOne()  ,       ,  ,                   (              1)      :
> db.storeCollection.findOne({'version':'3.5'})  
{  
        "_id" : ObjectId("4ef970f23c1fc4613425accc"),  
        "version" : "3.5",  
        "segment" : "e3ol6"  
}  
7、      
  find()  ,        ,            。
8、    
     remove()  ,         ,      :
> db.storeCollection.remove({'version':'3.5'})  
> db.storeCollection.findOne()  
null  
9、    
       ensureIndex(keypattern[,options])  ,      :
> use pagedb  
switched to db pagedb  
> db.page.ensureIndex({'title':1, 'url':-1})  
> db.system.indexes.find()  
{ "name" : "_id_", "ns" : "pagedb.page", "key" : { "_id" : 1 }, "v" : 0 }  
{ "name" : "_id_", "ns" : "pagedb.system.users", "key" : { "_id" : 1 }, "v" : 0}  
{ "_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()      ,      :
> db.page.getIndexes()  
[  
        {  
                "name" : "_id_",  
                "ns" : "pagedb.page",  
                "key" : {  
                        "_id" : 1  
                },  
                "v" : 0  
        },  
        {  
                "_id" : ObjectId("4ef977633c1fc4613425accd"),  
                "ns" : "pagedb.page",  
                "key" : {  
                        "title" : 1,  
                        "url" : -1  
                },  
                "name" : "title_1_url_-1",  
                "v" : 0  
        }  
]  
  ,              ,    db.system.indexes.find()  。
11、    
           :
db.mycoll.dropIndex(name)  
db.mycoll.dropIndexes()  
           ,              。
12、    
       reIndex()         ,      :
> db.page.reIndex()  
{  
        "nIndexesWas" : 2,  
        "msg" : "indexes dropped for collection",  
        "ok" : 1,  
        "nIndexes" : 2,  
        "indexes" : [  
                {  
                        "name" : "_id_",  
                        "ns" : "pagedb.page",  
                        "key" : {  
                                "_id" : 1  
                        },  
                        "v" : 0  
                },  
                {  
                        "_id" : ObjectId("4ef977633c1fc4613425accd"),  
                        "ns" : "pagedb.page",  
                        "key" : {  
                                "title" : 1,  
                                "url" : -1  
                        },  
                        "name" : "title_1_url_-1",  
                        "v" : 0  
                }  
        ],  
        "ok" : 1  
}  
13、       
use fragment
db.baseSe.count()
    ,    :
> use fragment  
switched to db fragment  
> db.baseSe.count()  
36749  
        fragment baseSe      。
14、          
use fragment
db.baseSe.find().count()
find()        ,         ,    :
> use fragment  
switched to db fragment  
> db.baseSe.find().count()  
36749  
               ,          fragment baseSe          。
15、                   
use fragment
> db.baseSe.storageSize()
142564096
16、                 
> db.baseSe.totalSize()
144096000
       ,     (        )       。

 
         四、MongoDB起動と終了
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+\/")
       ,    ,         :
{  
        "user" : "admin",  
        "readOnly" : false,  
        "pwd" : "995d2143e0bf79cba24b58b3e41852cd"  
}  
3、    
db.auth("admin", ",%F23_kj~00Opoo0+\/")
       。        :
{  
        "user" : "admin",  
        "readOnly" : false,  
        "pwd" : "995d2143e0bf79cba24b58b3e41852cd"  
}  
       ,      ,          ,    :
db.system.users.find()  
{ "_id" : ObjectId("4ef940a13c1fc4613425acc8"), "user" : "admin", "readOnly" : false, "pwd" : "995d2143e0bf79cba24b58b3e41852cd" }  
  ,    ,            :
db.system.users.find()  
error: {  
        "$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1", "code" : 10057  
}  
4、       (     )  
db.runCommand({fsync:1,lock:1})
  :
           ,          ,             。    ,      :
{  
        "info" : "now locked against writes, use db.$cmd.sys.unlock.findOne() to unlock",  
        "ok" : 1  
}  
5、       
db.currentOp()
  :
        :
{  
        "inprog" : [ ],  
        "fsyncLock" : 1,  
        "info" : "use db.$cmd.sys.unlock.findOne() to terminate the fsync write/snapshot lock"  
}  
  ,fsyncLock 1  MongoDB fsync  (            )              
6、  
use admin
db.$cmd.sys.unlock.findOne()
  :
    ,      :
{ "ok" : 1, "info" : "unlock requested" }  
           :
db.currentOp()
      :
{ "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
         ,      :
mongoimport --help  
options:  
  --help                  produce help message  
  -v [ --verbose ]        be more verbose (include multiple times for more  
                          verbosity e.g. -vvvvv)  
  -h [ --host ] arg       mongo host to connect to ( /s1,s2 for sets)  
  --port arg              server port. Can also use --host hostname:port  
  --ipv6                  enable IPv6 support (disabled by default)  
  -u [ --username ] arg   username  
  -p [ --password ] arg   password  
  --dbpath arg            directly access mongod database files in the given  
                          path, instead of connecting to a mongod  server -  
                          needs to lock the data directory, so cannot be used  
                          if a mongod is currently accessing the same path  
  --directoryperdb        if dbpath specified, each db is in a separate  
                          directory  
  -d [ --db ] arg         database to use  
  -c [ --collection ] arg collection to use (some commands)  
  -f [ --fields ] arg     comma separated list of field names e.g. -f name,age  
  --fieldFile arg         file with fields names - 1 per line  
  --ignoreBlanks          if given, empty fields in csv and tsv will be ignored  
  --type arg              type of file to import.  default: json (json,csv,tsv)  
  --file arg              file to import from; if not specified stdin is used  
  --drop                  drop collection first  
  --headerline            CSV,TSV only - use first line as headers  
  --upsert                insert or update objects that already exist  
  --upsertFields arg      comma-separated fields for the query part of the  
                          upsert. You should make sure this is indexed  
  --stopOnError           stop importing at first error rather than continuing  
  --jsonArray             load a json array, not one item per line. Currently  
                          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       
         ,      :
mongoexport --help  
options:  
  --help                  produce help message  
  -v [ --verbose ]        be more verbose (include multiple times for more verbosity e.g. -vvvvv)  
  -h [ --host ] arg       mongo host to connect to ( /s1,s2 for sets)  
  --port arg              server port. Can also use --host hostname:port  
  --ipv6                  enable IPv6 support (disabled by default)  
  -u [ --username ] arg   username  
  -p [ --password ] arg   password  
  --dbpath arg            directly access mongod database files in the given  
                          path, instead of connecting to a mongod  server -  
                          needs to lock the data directory, so cannot be used  
                          if a mongod is currently accessing the same path  
  --directoryperdb        if dbpath specified, each db is in a separate directory  
  -d [ --db ] arg         database to use  
  -c [ --collection ] arg collection to use (some commands)  
  -f [ --fields ] arg     comma separated list of field names e.g. -f name,age  
  --fieldFile arg         file with fields names - 1 per line  
  -q [ --query ] arg      query filter, as a JSON string  
  --csv                   export to csv instead of json  
  -o [ --out ] arg        output file; if not specified, stdout is used  
  --jsonArray             output to a json array rather than one object per line  
  :
       -q        ,          ,    :
mongoexport -d page -c Article -q '{"spiderName": "mafengwoSpider"}' -f _id,title,content,images,publishDate,spiderName,url --jsonArray > mafengwoArticle.txt  
  ,         :
ERROR: too many positional options

 
         七、リモート接続管理
mongo -u admin -p admin 192.168.0.197:27017/pagedb  
  mongo    ,             ,      ,    :
mongo --help  
MongoDB shell version: 1.8.3  
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  
  --quiet               be less chatty  
  --port arg            port to connect to  
  --host arg            server to connect to  
  --eval arg            evaluate javascript  
  -u [ --username ] arg username for authentication  
  -p [ --password ] arg password for authentication  
  -h [ --help ]         show this usage information  
  --version             show version information  
  --verbose             increase verbosity  
  --ipv6                enable IPv6 support (disabled by default)  
2、  MongoDB   javascript      
            MongoDB      (  ,  mongo   192.168.0.184),                        (192.168.0.197),        :
> var x = new Mongo('192.168.0.1:27017')  
> var mdb = x.getDB('pagedb');  
> use mdb  
switched to db mdb  
> db  
mdb  
> mdb.page.findOne()  
{  
        "_id" : ObjectId("4eded6a5bf3bfa0014000003"),  
        "content" : "        ,  ...",  
        "pubdate" : "2006-03-19",  
        "title" : "  :         ",  
        "url" : "http://france.bytravel.cn/Scenery/528/cblsegdbl.html"  
}  
    MongoDB   JavaScript  ,                  ,       pagedb page  。
           ,             ,      ,  :
> var x = new Mongo('192.168.0.1:27017')  
> var mdb = x.getDB('pagedb', 'shirdrn', '(jkfFS$343$_\=\,.F@3');  
> use mdb  
switched to db mdb 

 
         八、可視化ツールmongoVUE
          ダウンロード先:http://www.mongovue.com/
          使用方法:http://www.cnblogs.com/shanyou/archive/2011/05/20/2052354.html