matsukaz's blog

Agile, node.js, ruby, AWS, cocos2d-xなどなどいろいろやってます

コンソール画面でのコマンド操作

MongoDBに対する操作は、基本的にコンソール画面から行うので、コマンドさえ理解出来れば大抵のことが出来ます。というわけで今回はコマンドの説明。


mongod/mongosへ接続

何はともあれ接続。コマンドは以下の通り。

> MONGODB_HOME/bin/mongo.exe [ホスト名]:[ポート番号]/[データベース名]

あとから接続先のデータベースを変更することも出来る。

> use [データベース名]

mongod/mongosの両方に接続できるけど、Sharding構成の場合は必ずmongosに接続すること。mongodに接続した場合は、他のmongodにShardingされている情報が取得出来ない。

mongosに接続した場合

> MONGODB_HOME/bin/mongo.exe localhost:28101/hoge
MongoDB shell version: 1.8.1
connecting to: localhost:28101/hoge
> db.user.count();
300000

mongodに接続した場合

> MONGODB_HOME/bin/mongo.exe localhost:28201/hoge
MongoDB shell version: 1.8.1
connecting to: localhost:28201/hoge
> db.user.count();
179974

ちなみに、Replica Set構成でPRIMARY以外に接続すると、コマンド実行時にPRIMARYじゃないとエラーメッセージが表示される。

MONGODB_HOME/bin/mongo.exe localhost:28212/hoge
MongoDB shell version: 1.8.1
connecting to: localhost:28212/hoge
s2:SECONDARY> db.user.count();
Tue Apr 19 00:42:17 uncaught exception: count failed: { "errmsg" : "not master", "ok" : 0 }

困ったらhelp

ほとんどのコマンドはhelpで説明が表示されるので、困ったらhelp。

> 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 <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

データベースの操作について分からない場合は、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,<slowms>) 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.[コレクション名].help()を実行する。

> show collections
system.indexes
user
> db.user.help();
DBCollection help
        db.user.find().help() - show DBCursor help
        db.user.count()
        db.user.dataSize()
        db.user.distinct( key ) - eg. db.user.distinct( 'x' )
        db.user.drop() drop the collection
        db.user.dropIndex(name)
        db.user.dropIndexes()
        db.user.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
        db.user.reIndex()
        db.user.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                      e.g. db.user.find( {x:77} , {name:1, x:1} )
        db.user.find(...).count()
        db.user.find(...).limit(n)
        db.user.find(...).skip(n)
        db.user.find(...).sort(...)
        db.user.findOne([query])
        db.user.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
        db.user.getDB() get DB object associated with collection
        db.user.getIndexes()
        db.user.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
        db.user.mapReduce( mapFunction , reduceFunction , <optional params> )
        db.user.remove(query)
        db.user.renameCollection( newName , <dropTarget> ) renames the collection.
        db.user.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
        db.user.save(obj)
        db.user.stats()
        db.user.storageSize() - includes free space allocated to this collection
        db.user.totalIndexSize() - size in bytes of all the indexes
        db.user.totalSize() - storage allocated for all data and indexes
        db.user.update(query, object[, upsert_bool, multi_bool])
        db.user.validate() - SLOW
        db.user.getShardVersion() - only for use with sharding

Replica Setに関するヘルプはrs.help()を実行する。

> rs.help()
        rs.status()                     { replSetGetStatus : 1 } checks repl set status
        rs.initiate()                   { replSetInitiate : null } initiates set with default settings
        rs.initiate(cfg)                { replSetInitiate : cfg } initiates set with configuration cfg
        rs.conf()                       get the current configuration object from local.system.replset
        rs.reconfig(cfg)                updates the configuration of a running replica set with cfg (disconnects)
        rs.add(hostportstr)             add a new member to the set with default attributes (disconnects)
        rs.add(membercfgobj)            add a new member to the set with extra attributes (disconnects)
        rs.addArb(hostportstr)          add a new member which is arbiterOnly:true (disconnects)
        rs.stepDown([secs])             step down as primary (momentarily) (disconnects)
        rs.freeze(secs)                 make a node ineligible to become primary for the time specified
        rs.remove(hostportstr)          remove a host from the replica set (disconnects)
        rs.slaveOk()                    shorthand for db.getMongo().setSlaveOk()

        db.isMaster()                   check who is primary

        reconfiguration helpers disconnect from the database so the shell will display
        an error, even if the command succeeds.
        see also http://<mongod_host>:28017/_replSet for additional diagnostic info

あとはshow xxxでデータベースやコレクションの情報を表示したりと。

> show dbs;
admin   (empty)
config  0.015625GB
hoge    0.1875GB
> show collections;
system.indexes
user

分かりづらいのはコマンドを実行するdb.runCommand(cmdObj)。db.listCommands()でコマンドの一覧が表示されるため、ここから必要なコマンドを探す。

> db.listCommands();
addShard: no-lock adminOnly  slaveOk
  add a new shard to the system

applyOps: no-lock
  no help defined

availableQueryOptions: no-lock
  no help defined

buildInfo: no-lock adminOnly  slaveOk
  get version #, etc.
  { buildinfo:1 }

closeAllDatabases: no-lock adminOnly  slaveOk
  Not supported sharded

collStats: no-lock
  no help defined

connPoolStats: no-lock
  stats about connection pool

connPoolSync: no-lock
  internal

convertToCapped: no-lock
  no help defined

copydb: no-lock
  no help defined

count: no-lock
  no help defined

cursorInfo: no-lock
   example: { cursorInfo : 1 }

dataSize: no-lock
  no help defined

dbStats: no-lock
  no help defined

distinct: no-lock
  { distinct : 'collection name' , key : 'a.b' , query : {} }

drop: no-lock
  no help defined

dropDatabase: no-lock
  no help defined

dropIndexes: no-lock
  no help defined

enableSharding: no-lock adminOnly  slaveOk
  Enable sharding for a db. (Use 'shardcollection' command afterwards.)
    { enablesharding : "<dbname>" }


features: no-lock
  return build level feature settings

filemd5: no-lock
   example: { filemd5 : ObjectId(aaaaaaa) , root : "fs" }

findAndModify: no-lock
  no help defined

forceerror: no-lock
  for testing purposes only.  forces a user assertion exception

fsync: no-lock adminOnly  slaveOk
  no help defined

geoNear: no-lock
  http://www.mongodb.org/display/DOCS/Geospatial+Indexing#GeospatialIndexing-geoNearCommand

getCmdLineOpts: no-lock adminOnly  slaveOk
  get argv

getLastError: no-lock
  check for an error on the last command executed

getParameter: no-lock adminOnly  slaveOk
  get administrative option(s)
  example:
  { getParameter:1, notablescan:1 }
  supported so far:
    quiet
    notablescan
    logLevel
    syncdelay
  { getParameter:'*' } to get everything


getPrevError: no-lock
  get previous error (since last reseterror command)

getShardMap: no-lock adminOnly  slaveOk
  internal

getShardVersion: no-lock adminOnly  slaveOk
   example: { getShardVersion : 'alleyinsider.foo'  }

group: no-lock
  no help defined

isMaster: no-lock
  test if this is master half of a replica pair

isdbgrid: no-lock
  no help defined

listCommands: no-lock
  get a list of all db commands

listDatabases: no-lock adminOnly  slaveOk
  list databases on cluster

listShards: no-lock adminOnly  slaveOk
  list all shards of the system

logRotate: no-lock adminOnly  slaveOk
  no help defined

mapreduce: no-lock
  no help defined

moveChunk: no-lock adminOnly  slaveOk
  { movechunk : 'test.foo' , find : { num : 1 } , to : 'localhost:30001' }

movePrimary: no-lock adminOnly  slaveOk
   example: { moveprimary : 'foo' , to : 'localhost:9999' }

netstat: no-lock adminOnly  slaveOk
   shows status/reachability of servers in the cluster

ping: no-lock
  a way to check that the server is alive. responds immediately even if server is in a db lock.

reIndex: no-lock
  no help defined

removeShard: no-lock adminOnly  slaveOk
  remove a shard to the system.

renameCollection: no-lock
  no help defined

repairDatabase: no-lock
  no help defined

replSetGetStatus: no-lock adminOnly  slaveOk
  Not supported through mongos

resetError: no-lock
  no help defined

serverStatus: no-lock
  no help defined

setParameter: no-lock adminOnly  slaveOk
  set administrative option(s)
  example:
  { setParameter:1, notablescan:true }
  supported so far:
    notablescan
    logLevel
    quiet


shardCollection: no-lock adminOnly  slaveOk
  Shard a collection.  Requires key.  Optional unique. Sharding must already be enabled for the database.
    { enablesharding : "<dbname>" }


shutdown: no-lock adminOnly  slaveOk
  shutdown the database.  must be ran against admin db and either (1) ran from localhost or (2) authenticated.


split: no-lock adminOnly  slaveOk
   example: - split the shard that contains give key
   { split : 'alleyinsider.blog.posts' , find : { ts : 1 } }
   example: - split the shard that contains the key with this as the middle
   { split : 'alleyinsider.blog.posts' , middle : { ts : 1 } }
   NOTE: this does not move move the chunks, it merely creates a logical seperation


top: read-lock adminOnly  slaveOk
  usage by collection

validate: no-lock
  no help defined

whatsmyuri: no-lock
  {whatsmyuri:1}