概要
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
などのコレクション名は表示されないが、このコマンドで表示させます
- adminデータベースで
-
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 }