LoginSignup
256

More than 5 years have passed since last update.

MongoDBコマンド一覧(自分用メモ)

Last updated at Posted at 2015-12-11

MongoDBを触る機会があったので、コマンド一覧をまとめました。タイトルにあるように自分が使うコマンドのみ記載していますので、コマンドに偏りがあるのはスルーでお願いします。

なお今回は、MongoDBのバージョン3.0.7を利用します。

MongoDBへの接続

$ mongo 「ホスト名」/「DB名」 -u 「ユーザー名」 -p
MongoDB shell version: 3.0.7
Enter password:「パスワードを入力」

ローカルホストに接続する場合は、下記のようにホスト名を省略する事が可能です。

$ mongo 「DB名」 -u 「ユーザー名」 -p

ローカルホストで且つユーザー認証を有効化していない場合は、下記を入力する事でログインする事も可能です。

$ mongo

DB操作

# DB作成
use 「DB名」;

# DB切り替え
use 「DB名」;

# DB削除
use 「削除したいDB名」;
db.dropDatabase();

# DB一覧確認
show dbs;

use 「DB名」;と入力するだけで、DBが作成できてしまいます。
MySQLに慣れてると、少し違和感がありますね。

コレクション操作

コレクションは、MySQLでいう所のテーブルのようなものです。

# コレクション一覧確認
use 「DB名」;
show collections;

# コレクション追加
use 「DB名」;
db.createCollection('「コレクション名」');

# コレクション削除
use 「DB名」;
db.「コレクション名」.drop();

ユーザーまわり

# ユーザーの一覧確認
use admin;
db.system.users.find();

# 新規ユーザー作成(ここではrootの権限を持ったユーザーを作成してます)
use admin;
db.createUser(
  {
    user:"「作成したいユーザー名」",
    pwd:"「パスワード」",
    roles:[
       { 
           "role" : "root",
            "db" : "admin"
       }
    ]
  } 
);

※useで指定しているDBと、rolesで指定しているDBは同じじゃなくても問題ありません。
※MongoDBにログインする場合、useで指定したDBに対してログインして下さい。
※roleはrootである必要はないので、必要な権限のroleに変更して下さい。


# ユーザー権限変更(ここでは任意のユーザーの権限をdbOwnerに変更しています)
use 「DB名」;
db.updateUser(
  "「ユーザー名」",
  {
    roles:
    [
      {
        role: "dbOwner",
        db: "「DB名」"
      }
    ]
  }
);

※roleはdbOwnerである必要はないので、必要な権限のroleに変更して下さい。


# ユーザー削除
use admin;
db.system.users.remove(
    {"_id" : "「DB名」.「ユーザー名」"}
);

Index

# Index確認
use 「DB名」;
db.「コレクション名」.getIndexes();

# Index作成(timeに対してをIndexを作成)
use 「DB名」;
db.「コレクション名」.ensureIndex({"time":1},{background:1});

その他

helpと入力する事により、ヘルプを表示させる事が出来ます。

> 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 Shellはtabキーによるコマンド補完をサポートしています。
コマンドを入力した後に、tabキーを入力すると以下のようにコマンドの候補を表示してくれます。

> db.
db.adminCommand(               db.grantRolesToUser(
db.auth(                       db.group(
db.changeUserPassword(         db.groupcmd(
db.cloneCollection(            db.groupeval(
db.cloneDatabase(              db.hasOwnProperty(
db.commandHelp(                db.help(
db.constructor                 db.hostInfo(
db.copyDatabase(               db.isMaster(
db.createCollection(           db.killOP(
db.createRole(                 db.killOp(
db.createUser(                 db.listCommands(
db.currentOP(                  db.loadServerScripts(
db.currentOp(                  db.logout(
db.dbEval(                     db.printCollectionStats(
db.dropAllRoles(               db.printReplicationInfo(
db.dropAllUsers(               db.printShardingStatus(
db.dropDatabase(               db.printSlaveReplicationInfo(
db.dropRole(                   db.propertyIsEnumerable(
db.dropUser(                   db.prototype
db.eval(                       db.removeUser(
db.forceError(                 db.repairDatabase(
db.fsyncLock(                  db.resetError(
db.fsyncUnlock(                db.revokePrivilegesFromRole(
db.getCollection(              db.revokeRolesFromRole(
db.getCollectionInfos(         db.revokeRolesFromUser(
db.getCollectionNames(         db.runCommand(
db.getLastError(               db.serverBits(
db.getLastErrorCmd(            db.serverBuildInfo(
db.getLastErrorObj(            db.serverCmdLineOpts(
db.getLogComponents(           db.serverStatus(
db.getMongo(                   db.setLogLevel(
db.getName(                    db.setProfilingLevel(
db.getPrevError(               db.setSlaveOk(
db.getProfilingLevel(          db.setWriteConcern(
db.getProfilingStatus(         db.shutdownServer(
db.getReplicationInfo(         db.stats(
db.getRole(                    db.toLocaleString(
db.getRoles(                   db.toString(
db.getSiblingDB(               db.tojson(
db.getSisterDB(                db.unsetWriteConcern(
db.getSlaveOk(                 db.updateRole(
db.getUser(                    db.updateUser(
db.getUsers(                   db.upgradeCheck(
db.getWriteConcern(            db.upgradeCheckAllDBs(
db.grantPrivilegesToRole(      db.valueOf(
db.grantRolesToRole(           db.version(

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
256