Skip to content

24. MongoDB DB Commands

이번 포스팅에서는 DB 명령어에 대해 알아보도록 하겠습니다.

그 동안 앞선 글에서 다루지 않았던 수많은 MongoDB의 명령어에는 어떤 것들이 있는지 훑어볼 수 있는 기회가 될 것입니다 (물론 하나하나 다루지는 않습니다. 여기서 다루지 않은 명령어들은 MongoDB의 공식 도큐먼트 페이지를 통해 알아보기 바랍니다).

우선 db.listCommands() 명령을 통해 DB 명령어의 리스트를 살펴보도록 하겠습니다:

> db.listCommands()
_isSelf: no-lock
  { _isSelf : 1 } INTERNAL ONLY

_migrateClone: no-lock adminOnly  slaveOk
  internal - should not be called directly

_recvChunkAbort: no-lock adminOnly  slaveOk
  internal - should not be called directly

_recvChunkCommit: no-lock adminOnly  slaveOk
  internal - should not be called directly

_recvChunkStart: write-lock adminOnly  slaveOk
  internal - should not be called directly

_recvChunkStatus: no-lock adminOnly  slaveOk
  internal - should not be called directly

_transferMods: no-lock adminOnly  slaveOk
  internal - should not be called directly

aggregate: no-lock
  { pipeline : [ { <data-pipe-op>: {...}}, ... ] }

applyOps: write-lock
  internal (sharding)
  { applyOps : [ ] , preCondition : [ { ns : ... , q : ... , res : ... } ] }

authenticate: no-lock
  internal

availableQueryOptions: no-lock
  no help defined

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

checkShardingIndex: no-lock
  Internal command.


clone: write-lock
  clone this database from an instance of the db on another host
  { clone : "host13" }

cloneCollection: no-lock
  { cloneCollection: <collection>, from: <host> [,query: <query_filter>] [,copyIndexes:<bool>] }
  Copies a collection from one server to another. Do not use on a single server as the destination is placed at the same db.collection (namespace) as the source.


cloneCollectionAsCapped: write-lock
  { cloneCollectionAsCapped:<fromName>, toCollection:<toName>, size:<sizeInBytes> }

closeAllDatabases: write-lock adminOnly  slaveOk
  Close all database files.
  A new request will cause an immediate reopening; thus, this is mostly for testing purposes.

collMod: write-lock
  Sets collection options.
  Example: { collMod: 'foo', usePowerOf2Sizes:true }
  Example: { collMod: 'foo', index: {keyPattern: {a: 1}, expireAfterSeconds: 600} }

collStats: read-lock
  { collStats:"blog.posts" , scale : 1 } scale divides sizes e.g. for KB use 1024
      avgObjSize - in bytes

compact: no-lock
  compact collection
  warning: this operation blocks the server and is slow. you can cancel with cancelOp()
  { compact : <collection_name>, [force:<bool>], [validate:<bool>],
    [paddingFactor:<num>], [paddingBytes:<num>] }
    force - allows to run on a replica set primary
    validate - check records are noncorrupt before adding to newly compacting extents. slower but safer (defaults to true in this version)


connPoolStats: no-lock
  stats about connection pool

connPoolSync: no-lock
  internal

connectionStatus: no-lock
  Returns connection-specific information such as logged-in users

convertToCapped: write-lock
  { convertToCapped:<fromCollectionName>, size:<sizeInBytes> }

copydb: no-lock adminOnly  slaveOk
  copy a database from another host to this host
  usage: {copydb: 1, fromhost: <hostname>, fromdb: <db>, todb: <db>[, slaveOk: <bool>, username: <username>, nonce: <nonce>, key: <key>]}

copydbgetnonce: write-lock adminOnly  slaveOk
  get a nonce for subsequent copy db request from secure server
  usage: {copydbgetnonce: 1, fromhost: <hostname>}

count: read-lock
  count objects in collection

create: write-lock
  create a collection explicitly
  { create: <ns>[, capped: <bool>, size: <collSizeInBytes>, max: <nDocs>] }

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

dataSize: read-lock
  determine data size for a set of data in a certain range
  example: { dataSize:"blog.posts", keyPattern:{x:1}, min:{x:10}, max:{x:55} }
  min and max parameters are optional. They must either both be included or both omitted
  keyPattern is an optional parameter indicating an index pattern that would be usefulfor iterating over the min/max bounds. If keyPattern is omitted, it is inferred from the structure of min.
  note: This command may take a while to run

dbHash: read-lock
  no help defined

dbStats: read-lock
  Get stats on a database. Not instantaneous. Slower for databases with large .ns files.
  Example: { dbStats:1, scale:1 }

diagLogging: write-lock adminOnly  slaveOk
  http://dochub.mongodb.org/core/monitoring#MonitoringandDiagnostics-DatabaseRecord%2FReplay%28diagLoggingcommand%29

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

driverOIDTest: no-lock
  no help defined

drop: write-lock
  drop a collection
  {drop : <collectionName>}

dropDatabase: write-lock
  drop (delete) this database

dropIndexes: write-lock
  drop indexes for a collection

eval: no-lock
  Evaluate javascript at the server.
  http://dochub.mongodb.org/core/serversidecodeexecution

features: no-lock
  return build level feature settings

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

findAndModify: write-lock
  { findAndModify: "collection", query: {processed:false}, update: {$set: {processed:true}}, new: true}
  { findAndModify: "collection", query: {processed:false}, remove: true, sort: {priority:-1}}
  Either update or remove is required, all other fields have default values.
  Output is in the "value" field


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

fsync: no-lock adminOnly  slaveOk
  http://dochub.mongodb.org/core/fsynccommand

geoNear: read-lock
  http://dochub.mongodb.org/core/geo#GeospatialIndexing-geoNearCommand

geoSearch: read-lock
  no help defined

geoWalk: read-lock
  no help defined

getCmdLineOpts: no-lock adminOnly  slaveOk
  get argv

getLastError: no-lock
  return error status of the last operation on this connection
  options:
    { fsync:true } - fsync before returning, or wait for journal commit if running with --journal
    { j:true } - wait for journal commit if running with --journal
    { w:n } - await replication to n servers (including self) before returning
    { wtimeout:m} - timeout for w in m milliseconds

getLog: no-lock adminOnly  slaveOk
  { getLog : '*' }  OR { getLog : 'global' }

getParameter: no-lock adminOnly  slaveOk
  get administrative option(s)
  example:
  { getParameter:1, notablescan:1 }
  supported:
    enableLocalhostAuthBypass
    enableTestCommands
    logLevel
    logUserIds
    notablescan
    quiet
    releaseConnectionsAfterResponse
    replApplyBatchSize
    replIndexPrefetch
    supportCompatibilityFormPrivilegeDocuments
    syncdelay
    textSearchEnabled
    ttlMonitorEnabled
  { getParameter:'*' } to get everything


getPrevError: no-lock
  check for errors since last reseterror commandcal

getShardMap: no-lock adminOnly  slaveOk
  internal

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

getnonce: no-lock
  internal

getoptime: no-lock
  internal

group: read-lock
  http://dochub.mongodb.org/core/aggregation

handshake: no-lock
  internal

hostInfo: no-lock
  returns information about the daemon's host

isMaster: no-lock
  Check if this server is primary for a replica pair/set; also if it is --master or --slave in simple master/slave setups.
  { isMaster : 1 }

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

listDatabases: no-lock adminOnly  slaveOk
  list databases on this server

logRotate: no-lock adminOnly  slaveOk
  no help defined

logout: no-lock
  de-authenticate

mapReduce: no-lock
  Run a map/reduce operation on the server.
  Note this is used for aggregation, not querying, in MongoDB.
  http://dochub.mongodb.org/core/mapreduce

mapreduce.shardedfinish: no-lock
  no help defined

medianKey: no-lock
  Deprecated internal command. Use splitVector command instead.


moveChunk: no-lock adminOnly  slaveOk
  should not be calling this directly

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

profile: write-lock
  enable or disable performance profiling
  { profile : <n> }
  0=off 1=log slow ops 2=log all
  -1 to get current values
  http://dochub.mongodb.org/core/databaseprofiler

reIndex: write-lock
  re-index a collection

renameCollection: write-lock adminOnly  slaveOk
   example: { renameCollection: foo.a, to: bar.b }

repairDatabase: write-lock
  repair database.  also compacts. note: slow.

replSetElect: no-lock adminOnly  slaveOk
  internal

replSetFreeze: no-lock adminOnly  slaveOk
  { replSetFreeze : <seconds> }'freeze' state of member to the extent we can do that.  What this really means is that
  this node will not attempt to become primary until the time period specified expires.
  You can call again with {replSetFreeze:0} to unfreeze sooner.
  A process restart unfreezes the member also.

  http://dochub.mongodb.org/core/replicasetcommands

replSetFresh: no-lock adminOnly  slaveOk
  internal

replSetGetRBID: no-lock adminOnly  slaveOk
  internal

replSetGetStatus: no-lock adminOnly  slaveOk
  Report status of a replica set from the POV of this server
  { replSetGetStatus : 1 }
  http://dochub.mongodb.org/core/replicasetcommands

replSetHeartbeat: no-lock adminOnly  slaveOk
  internal

replSetInitiate: no-lock adminOnly  slaveOk
  Initiate/christen a replica set.
  http://dochub.mongodb.org/core/replicasetcommands

replSetMaintenance: no-lock adminOnly  slaveOk
  { replSetMaintenance : bool }
  Enable or disable maintenance mode.

replSetReconfig: no-lock adminOnly  slaveOk
  Adjust configuration of a replica set
  { replSetReconfig : config_object }
  http://dochub.mongodb.org/core/replicasetcommands

replSetStepDown: no-lock adminOnly  slaveOk
  { replSetStepDown : <seconds> }
  Step down as primary.  Will not try to reelect self for the specified time period (1 minute if no numeric secs value specified).
  (If another member with same priority takes over in the meantime, it will stay primary.)
  http://dochub.mongodb.org/core/replicasetcommands

replSetSyncFrom: no-lock adminOnly  slaveOk
  { replSetSyncFrom : "host:port" }
  Change who this member is syncing from.

resetError: no-lock
  reset error state (used with getpreverror)

resync: write-lock adminOnly  slaveOk
  resync (from scratch) an out of date replica slave.
  http://dochub.mongodb.org/core/masterslave

serverStatus: no-lock
  returns lots of administrative server statistics

setParameter: no-lock adminOnly  slaveOk
  set administrative option(s)
  { setParameter:1, <param>:<value> }
  supported:
    enableLocalhostAuthBypass
    enableTestCommands
    logLevel
    logUserIds
    notablescan
    quiet
    releaseConnectionsAfterResponse
    replApplyBatchSize
    replIndexPrefetch
    supportCompatibilityFormPrivilegeDocuments
    syncdelay
    textSearchEnabled
    ttlMonitorEnabled


setShardVersion: no-lock adminOnly  slaveOk
   example: { setShardVersion : 'alleyinsider.foo' , version : 1 , configdb : '' }

shardConnPoolStats: no-lock
  stats about the shard connection pool

shardingState: write-lock adminOnly  slaveOk
  no help defined

shutdown: no-lock adminOnly  slaveOk
  shutdown the database.  must be ran against admin db and either (1) ran from localhost or (2) authenticated. If this is a primary in a replica set and there is no member within 10 seconds of its optime, it will not shutdown without force : true.  You can also specify timeoutSecs : N to wait N seconds for other members to catch up.

splitChunk: no-lock adminOnly  slaveOk
  internal command usage only
  example:
   { splitChunk:"db.foo" , keyPattern: {a:1} , min : {a:100} , max: {a:200} { splitKeys : [ {a:150} , ... ]}

splitVector: no-lock
  Internal command.
  examples:
    { splitVector : "blog.post" , keyPattern:{x:1} , min:{x:10} , max:{x:20}, maxChunkSize:200 }
    maxChunkSize unit in MBs
    May optionally specify 'maxSplitPoints' and 'maxChunkObjects' to avoid traversing the whole chunk

    { splitVector : "blog.post" , keyPattern:{x:1} , min:{x:10} , max:{x:20}, force: true }
    'force' will produce one split point even if data is small; defaults to false
  NOTE: This command may take a while to run

text: read-lock
  no help defined

top: no-lock adminOnly  slaveOk
  usage by collection, in micros

touch: no-lock
  touch collection
  Page in all pages of memory containing every extent for the given collection
  { touch : <collection_name>, [data : true] , [index : true] }
   at least one of data or index must be true; default is both are false


unsetSharding: no-lock adminOnly  slaveOk
   example: { unsetSharding : 1 }

validate: read-lock
  Validate contents of a namespace by scanning its data structures for correctness.  Slow.
  Add full:true option to do a more thorough check

whatsmyuri: no-lock
  {whatsmyuri:1}

writeBacksQueued: no-lock adminOnly  slaveOk
  Returns whether there are operations in the writeback queue at the time the command was called. This is an internal command

writebacklisten: no-lock adminOnly  slaveOk
  internal

어마어마한 명령어 집단을 발견하게 될 것이다. 이 중 몇가지 명령어들에 대해 간략히 알아보도록 하겠습니다.


buildInfo

  • 프로토타입: db.runCommand({{buildInfo : 1}})
  • 설명: MongoDB 서버의 버전과 호스트 OS에 대한 정보를 출력합니다.
  • 예:
> db.runCommand({buildInfo:1})
{
  "version" : "2.4.8",
  "gitVersion" : "a350fc38922fbda2cec8d5dd842237b904eafc14",
  "sysInfo" : "Linux ip-10-2-29-40 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_49",
  "loaderFlags" : "-fPIC -pthread -rdynamic",
  "compilerFlags" : "-Wnon-virtual-dtor -Woverloaded-virtual -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -pipe -fno-builtin-memcmp -O3",
  "allocator" : "tcmalloc",
  "versionArray" : [
    2,
    4,
    8,
    0
  ],
  "javascriptEngine" : "V8",
  "bits" : 64,
  "debug" : false,
  "maxBsonObjectSize" : 16777216,
  "ok" : 1
}

collStats

  • 프로토타입: db.runCommand({collStats: collection})
  • 설명: 데이터 사이즈, 할당된 저장 공간 크기, 인덱스의 크기 등을 포함한 컬렉션에 대한 정보를 출력합니다.
  • 예: orders 컬렉션에 대한 정보를 알아보려면:
> db.runCommand({collStats: "orders"})
{
  "ns" : "amazon.orders",
  "count" : 4,
  "size" : 832,
  "avgObjSize" : 208,
  "storageSize" : 16384,
  "numExtents" : 1,
  "nindexes" : 1,
  "lastExtentSize" : 16384,
  "paddingFactor" : 1,
  "systemFlags" : 1,
  "userFlags" : 0,
  "totalIndexSize" : 8176,
  "indexSizes" : {
    "_id_" : 8176
  },
  "ok" : 1
}

과 같이 입력합니다.


distinct

  • 프로토타입: db.runCommand({distinct : collection, key: key, query: query}) 또는 db.collection.distinct({key: key, query: query})
  • 설명: 주어진 컬렉션에 있어 매칭되는 쿼리에 대해 키 값에 대해 구별되는 값들을 얻습니다.
  • 예: 우선 다음과 같이 도큐먼트를 준비합니다.
db.orders.insert({cust_id: "abc123", ord_date: new Date("Oct 04, 2012"), status: 'A', price: 25, items: [ { sku: "mmm", qty: 5, price: 2.5 }, { sku: "nnn", qty: 4, price: 2.5 } ]})
db.orders.insert({cust_id: "abc123", ord_date: new Date("Nov 03, 2011"), status: 'B', price: 40, items: [ { sku: "mmm", qty: 7, price: 4.5 }, { sku: "nnn", qty: 3, price: 3.5 } ]})
db.orders.insert({cust_id: "def123", ord_date: new Date("Feb 03, 2014"), status: 'C', price: 15, items: [ { sku: "mmm", qty: 5, price: 4.0 }, { sku: "nnn", qty: 8, price: 3.0 } ]})
db.orders.insert({cust_id: "def123", ord_date: new Date("Mar 03, 2014"), status: 'D', price: 17, items: [ { sku: "mmm", qty: 6, price: 2.0 }, { sku: "nnn", qty: 4, price: 1.7 } ]})
> db.orders.find().pretty()
{
  "_id" : ObjectId("5315ea0b4d478aa3741c0c26"),
  "cust_id" : "abc123",
  "ord_date" : ISODate("2012-10-03T15:00:00Z"),
  "status" : "A",
  "price" : 25,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 5,
      "price" : 2.5
    },
    {
      "sku" : "nnn",
      "qty" : 4,
      "price" : 2.5
    }
  ]
}
{
  "_id" : ObjectId("5315ea0c4d478aa3741c0c27"),
  "cust_id" : "abc123",
  "ord_date" : ISODate("2011-11-02T15:00:00Z"),
  "status" : "B",
  "price" : 40,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 7,
      "price" : 4.5
    },
    {
      "sku" : "nnn",
      "qty" : 3,
      "price" : 3.5
    }
  ]
}
{
  "_id" : ObjectId("5315ea0d4d478aa3741c0c28"),
  "cust_id" : "def123",
  "ord_date" : ISODate("2014-02-02T15:00:00Z"),
  "status" : "C",
  "price" : 15,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 5,
      "price" : 4
    },
    {
      "sku" : "nnn",
      "qty" : 8,
      "price" : 3
    }
  ]
}
{
  "_id" : ObjectId("5315ea0e4d478aa3741c0c29"),
  "cust_id" : "def123",
  "ord_date" : ISODate("2014-03-02T15:00:00Z"),
  "status" : "D",
  "price" : 17,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 6,
      "price" : 2
    },
    {
      "sku" : "nnn",
      "qty" : 4,
      "price" : 1.7
    }
  ]
}
{
  "_id" : ObjectId("53171bc266ff8f8cb78dc5e8"),
  "cust_id" : "abc123",
  "ord_date" : ISODate("2012-10-03T15:00:00Z"),
  "status" : "A",
  "price" : 25,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 5,
      "price" : 2.5
    },
    {
      "sku" : "nnn",
      "qty" : 4,
      "price" : 2.5
    }
  ]
}
{
  "_id" : ObjectId("53171bc366ff8f8cb78dc5e9"),
  "cust_id" : "abc123",
  "ord_date" : ISODate("2011-11-02T15:00:00Z"),
  "status" : "B",
  "price" : 40,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 7,
      "price" : 4.5
    },
    {
      "sku" : "nnn",
      "qty" : 3,
      "price" : 3.5
    }
  ]
}
{
  "_id" : ObjectId("53171bc466ff8f8cb78dc5ea"),
  "cust_id" : "def123",
  "ord_date" : ISODate("2014-02-02T15:00:00Z"),
  "status" : "C",
  "price" : 15,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 5,
      "price" : 4
    },
    {
      "sku" : "nnn",
      "qty" : 8,
      "price" : 3
    }
  ]
}
{
  "_id" : ObjectId("53171bc666ff8f8cb78dc5eb"),
  "cust_id" : "def123",
  "ord_date" : ISODate("2014-03-02T15:00:00Z"),
  "status" : "D",
  "price" : 17,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 6,
      "price" : 2
    },
    {
      "sku" : "nnn",
      "qty" : 4,
      "price" : 1.7
    }
  ]
}

그리고나서, 다음과 같이 입력해 봅니다:

> db.orders.distinct('cust_id')
[ "abc123", "def123" ]

위와 같이, 네 개의 도큐먼트에 대해 구별되는 고객 아이디(cust_id)가 "abc123" 및 "def123" 두 개임을 알 수 있습니다.


drop

  • 프로토타입: db.runCommand({drop: collection}) 또는 db.collection.drop()
  • 설명: 컬렉션의 모든 데이터를 삭제합니다.
  • 예:
> db.getCollectionNames()
[ "orders" "system.indexes", "system.users" ]
> db.runCommand({drop: "orders"})
{
  "nIndexesWas" : 1,
  "msg" : "indexes dropped for collection",
  "ns" : "amazon.orders",
  "ok" : 1
}
> db.getCollectionNames()
[ "system.indexes", "system.users" ]

dropDatabase

  • 프로토타입: db.runCommand({dropDatabase: 1})
  • 설명: 현재 데이터베이스("db") 내 모든 데이터를 삭제합니다.
  • 예:
> db.runCommand({dropDatabase: 1})
{ "dropped" : "amazon", "ok" : 1 }

> db.getCollectionNames()
[ ]

dropIndexes

  • 프로토타입: db.runCommand({dropIndexes : collection, index : name})
  • 설명: 컬렉션으로부터 name이라는 이름의 인덱스를 삭제한다. 모든 인덱스를 삭제하려면 name*로 입력합니다.

findAndModify

이 곳을 참고하기 바랍니다.


getLastError

  • 프로토타입: db.runCommand({getLastError : 1[, w : w[, wtimeout : timeout]]})
  • 설명: 마지막으로 수행한 오퍼레이션에 대한 에러를 체크하거나 상태 정보를 출력합니다. 이 명령은 현재 연결에서 w 슬레이브가 교쳬될 때까지(또는 timeout(milli 초) 시간이 흐를 때까지) 선택적으로 차단됩니다.
  • 예:
> db.runCommand({getLastError: 1})
{
  "n" : 0,
  "lastOp" : Timestamp(1394025626, 1),
  "connectionId" : 235758,
  "err" : null,
  "ok" : 1
}

isMaster

  • 프로토타입: db.runCommand({isMaster: 1})
  • 설명: 서버가 마스터인지 슬레이브인지 판단합니다.
  • 예:
> db.runCommand({isMaster: 1})
{
  "setName" : "rs-ds027799",
  "ismaster" : true,
  "secondary" : false,
  "hosts" : [
    "ds027799-a.mongolab.com:27799"
  ],
  "primary" : "ds027799-a.mongolab.com:27799",
  "me" : "ds027799-a.mongolab.com:27799",
  "maxBsonObjectSize" : 16777216,
  "maxMessageSizeBytes" : 48000000,
  "localTime" : ISODate("2014-03-05T13:42:21.998Z"),
  "ok" : 1
}

listDatabases

  • 프로토타입: db.runCommand({listDatabases: 1})
  • 설명: 서버 상의 모든 데이터베이스를 목록화합니다. admin 계정에서만 실행되는 명령어입니다.
  • 예:
> use admin
switched to db admin
> db.runCommand({listDatabases: 1})
{
  "databases" : [
    {
      "name" : "local",
      "sizeOnDisk" : 83886080,
      "empty" : false
    },
    {
      "name" : "test",
      "sizeOnDisk" : 218103808,
      "empty" : false
    }
  ],
  "totalSize" : 301989888,
  "ok" : 1
}

만약 MongoLab을 사용할 경우, use admin 명령을 통해 db admin으로 계정을 변경하여도 "권한이 없다"는 메시지가 출력될 것입니다.

즉, 클라우드(MongoDB-as-a-Service) 서비스를 통해 DB를 사용할 경우 admin 계정에 접근할 수 없습니다.


ping

  • 프로토타입: db.runCommand({ping: 1})
  • 설명: 서버가 살아있는지 확인한다.
  • 예:
> db.runCommand({ping: 1})
{ "ok" : 1 }

renameCollection

  • 프로토타입: db.runCommand({renameCollection: "a", to: "b"}) 또는 db.collection.renameCollection("targetCollectionName")
  • 설명: 컬렉션 ab로 이름을 변경합니다.
  • 예:
> db.getCollectionNames()
[ "orders", "system.indexes" ]
> db.orders.renameCollection("test")
{ "ok" : 1 }
> db.getCollectionNames()
[ "system.indexes", "test" ]

repairDatabase

  • 프로토타입: db.runCommand({repairDatabase: 1})
  • 설명: 현재 데이터베이스를 수리하고 컴팩트하게 만든다. 명령을 수행하는데 다소 시간이 소요될 수 있습니다.
  • 예:
> db.runCommand({repairDatabase: 1})
{ "ok" : 1 }

serverStatus

  • 프로토타입: db.runCommand({serverStatus: 1})
  • 설명: 서버에 대한 admin 통계를 얻습니다. admin 계정을 사용해야 합니다 ("use admin"). 따라서, MongLab과 같은 MongLab-as-a-Service 클라우드 플랫폼에서는 사용할 수 없습니다.
  • 예:
> use admin
switched to db admin
> db.runCommand({serverStatus: 1})
{
  "host" : "gchoi-ui-MacBook-Pro.local",
  "version" : "2.4.9",
  "process" : "mongod",
  "pid" : 1183,
  "uptime" : 402,
  "uptimeMillis" : NumberLong(402845),
  "uptimeEstimate" : 370,
  "localTime" : ISODate("2014-03-05T15:24:37.903Z"),
  "asserts" : {
    "regular" : 0,
    "warning" : 0,
    "msg" : 0,
    "user" : 5,
    "rollovers" : 0
  },
  "backgroundFlushing" : {
    "flushes" : 6,
    "total_ms" : 37,
    "average_ms" : 6.166666666666667,
    "last_ms" : 1,
    "last_finished" : ISODate("2014-03-05T15:23:55.111Z")
  },
  "connections" : {
    "current" : 1,
    "available" : 203,
    "totalCreated" : NumberLong(1)
  },
  "cursors" : {
    "totalOpen" : 0,
    "clientCursors_size" : 0,
    "timedOut" : 0
  },
  "dur" : {
    "commits" : 29,
    "journaledMB" : 0,
    "writeToDataFilesMB" : 0,
    "compression" : 0,
    "commitsInWriteLock" : 0,
    "earlyCommits" : 0,
    "timeMs" : {
      "dt" : 3038,
      "prepLogBuffer" : 0,
      "writeToJournal" : 0,
      "writeToDataFiles" : 0,
      "remapPrivateView" : 0
    }
  },
  "extra_info" : {
    "note" : "fields vary by platform",
    "page_faults" : 2030
  },
  "globalLock" : {
    "totalTime" : NumberLong(402844000),
    "lockTime" : NumberLong(589889),
    "currentQueue" : {
      "total" : 0,
      "readers" : 0,
      "writers" : 0
    },
    "activeClients" : {
      "total" : 0,
      "readers" : 0,
      "writers" : 0
    }
  },
  "indexCounters" : {
    "accesses" : 4,
    "hits" : 4,
    "misses" : 0,
    "resets" : 0,
    "missRatio" : 0
  },
  "locks" : {
    "." : {
      "timeLockedMicros" : {
        "R" : NumberLong(18220),
        "W" : NumberLong(589889)
      },
      "timeAcquiringMicros" : {
        "R" : NumberLong(698212),
        "W" : NumberLong(1426)
      }
    },
    "admin" : {
      "timeLockedMicros" : {
        "r" : NumberLong(2114),
        "w" : NumberLong(0)
      },
      "timeAcquiringMicros" : {
        "r" : NumberLong(34),
        "w" : NumberLong(0)
      }
    },
    "local" : {
      "timeLockedMicros" : {
        "r" : NumberLong(1038),
        "w" : NumberLong(0)
      },
      "timeAcquiringMicros" : {
        "r" : NumberLong(101),
        "w" : NumberLong(0)
      }
    },
    "db" : {
      "timeLockedMicros" : {
        "r" : NumberLong(332),
        "w" : NumberLong(0)
      },
      "timeAcquiringMicros" : {
        "r" : NumberLong(21),
        "w" : NumberLong(0)
      }
    },
    "orders" : {
      "timeLockedMicros" : {
        "r" : NumberLong(206),
        "w" : NumberLong(0)
      },
      "timeAcquiringMicros" : {
        "r" : NumberLong(13),
        "w" : NumberLong(0)
      }
    }
  },
  "network" : {
    "bytesIn" : 5133,
    "bytesOut" : 4893,
    "numRequests" : 54
  },
  "opcounters" : {
    "insert" : 5,
    "query" : 29,
    "update" : 0,
    "delete" : 0,
    "getmore" : 0,
    "command" : 47
  },
  "opcountersRepl" : {
    "insert" : 0,
    "query" : 0,
    "update" : 0,
    "delete" : 0,
    "getmore" : 0,
    "command" : 0
  },
  "recordStats" : {
    "accessesNotInMemory" : 0,
    "pageFaultExceptionsThrown" : 0,
    "db" : {
      "accessesNotInMemory" : 0,
      "pageFaultExceptionsThrown" : 0
    },
    "local" : {
      "accessesNotInMemory" : 0,
      "pageFaultExceptionsThrown" : 0
    },
    "orders" : {
      "accessesNotInMemory" : 0,
      "pageFaultExceptionsThrown" : 0
    }
  },
  "writeBacksQueued" : false,
  "mem" : {
    "bits" : 64,
    "resident" : 35,
    "virtual" : 2680,
    "supported" : true,
    "mapped" : 80,
    "mappedWithJournal" : 160
  },
  "metrics" : {
    "document" : {
      "deleted" : NumberLong(0),
      "inserted" : NumberLong(5),
      "returned" : NumberLong(22),
      "updated" : NumberLong(0)
    },
    "getLastError" : {
      "wtime" : {
        "num" : 4,
        "totalMillis" : 0
      },
      "wtimeouts" : NumberLong(0)
    },
    "operation" : {
      "fastmod" : NumberLong(0),
      "idhack" : NumberLong(0),
      "scanAndOrder" : NumberLong(0)
    },
    "queryExecutor" : {
      "scanned" : NumberLong(28)
    },
    "record" : {
      "moves" : NumberLong(0)
    },
    "repl" : {
      "apply" : {
        "batches" : {
          "num" : 0,
          "totalMillis" : 0
        },
        "ops" : NumberLong(0)
      },
      "buffer" : {
        "count" : NumberLong(0),
        "maxSizeBytes" : 268435456,
        "sizeBytes" : NumberLong(0)
      },
      "network" : {
        "bytes" : NumberLong(0),
        "getmores" : {
          "num" : 0,
          "totalMillis" : 0
        },
        "ops" : NumberLong(0),
        "readersCreated" : NumberLong(0)
      },
      "oplog" : {
        "insert" : {
          "num" : 0,
          "totalMillis" : 0
        },
        "insertBytes" : NumberLong(0)
      },
      "preload" : {
        "docs" : {
          "num" : 0,
          "totalMillis" : 0
        },
        "indexes" : {
          "num" : 0,
          "totalMillis" : 0
        }
      }
    },
    "ttl" : {
      "deletedDocuments" : NumberLong(0),
      "passes" : NumberLong(6)
    }
  },
  "ok" : 1
}

이상으로 MongoDB의 주요 명령어들에 대해 살펴 보았습니다. 하지만, 앞서 언급한 바와 같이 이외에도 명령어는 매우 많습니다. 물론 이들 중에는 거의 사용할 일이 없는 명령어들도 있긴 합니다.

다음 포스팅에서는 Capped Collection에 대해 알아보도록 하겠습니다.