LoginSignup
2
1

More than 5 years have passed since last update.

mongoシェルのdb,collectionにコマンドの追加

Posted at

概要

MongoDBのクライアントであるmongoシェルで使われるコマンドに新しいコマンドを追加します。mongoシェルで使われているのはJavascriptなのでそれを拡張します。

mongoシェルで使われているオブジェクト

https://github.com/mongodb/mongo/tree/master/src/mongo/shell
に定義しているJavascriptソースがありますので参照してください。

コマンド例 オブジェクト オブジェクト名 ソースファイル名
db.stats() データベース DB db.js
db.<collection>.find() コレクション DBCollection collection.js
cursor.next() カーソル DBQuery query.js

コマンドの追加例

下記の例のようなカスタムコマンドを.mongorc.jsに記述すれば、いつでも使えるようになります。

DB.prototype.cols = function() {
  this.getCollectionInfos().forEach(doc=>{print(doc.name)})
}

DB.prototype.infoOp = function() {
  var info = this.serverStatus()
  return {opcounters: info.opcounters}
}

DBCollection.prototype.infoUri = function() {
  var stats = this.stats()
  return {ns: stats.ns, uri: stats.wiredTiger.uri}
}

DBCollection.prototype.findx = function(query, fields, limit, skip, batchSize, options) {
  if (fields == undefined) 
      fields = {_id:0}
  else
      fields._id = 0;
  return this.find(query, fields, limit, skip, batchSize, options)
}
  • db.cols()
    • adminデータベースで show collectionsではsystem.versionなどのコレクション名は表示されないが、このコマンドで表示させます
  • db.infoOp()
    • db.serverStatus()はデータ項目が多いので、よく見る項目のみ表示するコマンドを作成
  • db.<collection>.infoUri()
    • コレクションの物理ファイル名を表示する
  • db.<collection>.findx()
    • _idフィールドを取得しないようにする

作成したコマンドの実行例

mongoシェル
> use admin
switched to db admin
> show collections
//何も表示されません
> db.cols()
system.keys
system.version
> db.infoOp()
{
        "opcounters" : {
                "insert" : 1,
                "query" : 32,
                "update" : 7,
                "delete" : 12,
                "getmore" : 0,
                "command" : 250
        }
}
> use test
switched to db test
> db.col2.insert({a:1})
WriteResult({ "nInserted" : 1 })
> db.col2.infoUri()
{
        "ns" : "test.col2",
        "uri" : "statistics:table:collection-0-2917259516752606342"
}
> db.col2.find()
{ "_id" : ObjectId("5cb812113c2c75c75408bfe7"), "a" : 1 }
> db.col2.findx()
{ "a" : 1 }
2
1
0

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