mongoインタラクティブシェルの使い方メモ

1. ワンライナーで。

$ echo 'show dbs;' | mongo
MongoDB shell version: 1.6.3
connecting to: test
> show dbs;
admin
local
test
> bye

簡単ですね。

2. JSファイルを食わせて。

以前のエントリと同様に既存のデータをMapReduceで集計してみます。
以下をmapReduce.jsとして作成します。

var m = function(){
    this.members.forEach(
        function(z) {
            emit( z.gender , { count : 1 } );
        }   
    );  
};
var r = function( key , values ){
    var total = 0;
    for ( var i=0; i<values.length; i++ ) { 
        total += values[i].count;
    }   
    return { count : total };
};
var res = db.SundayNightSyndrome.mapReduce(m,r);
print(db[res.result].find());
shellPrint(db[res.result].find());

で、mongo dbname filenameとしてやると結果を吐いてくれます。

$ mongo test mapReduce.js 
MongoDB shell version: 1.6.3
connecting to: test
# undefinedになっちゃう
DBQuery: test.tmp.mr.mapreduce_1305362204_57 -> undefined
# 結果が見やすい
{ "_id" : "female", "value" : { "count" : 4 } }
{ "_id" : "male", "value" : { "count" : 6 } }
$ 

以前のエントリと違い意図的にプリントしてやらないと結果を標準出力してくれません。print(db[res.result].find())ってやってみたんですがどうもインタラクティブにやった前回のように結果がうまくパースされない。
で、たどりついたのが JsDoc Reference - _global_ 。ここにshellPrint()というのがありまして、これで解決しました。

以降の例ではprint()の行は未適用とします。

3. JSファイルを食わせたあとでインタラクティブシェルを引き続き使いたい。

mongo dbname filename --shellでOK。

$ mongo test mapReduce.js --shell
MongoDB shell version: 1.6.3
connecting to: test
type "help" for help
{ "_id" : "female", "value" : { "count" : 4 } }
{ "_id" : "male", "value" : { "count" : 6 } }
>
> db[res.result].find();
{ "_id" : "female", "value" : { "count" : 4 } }
{ "_id" : "male", "value" : { "count" : 6 } }

4. インタラクティブシェルに入ってからJSファイルを読み込みたい。

load(filename)としてやります。

$ mongo
MongoDB shell version: 1.6.3
connecting to: test
> load('mapReduce.js');
{ "_id" : "female", "value" : { "count" : 4 } }
{ "_id" : "male", "value" : { "count" : 6 } }
>

そもそもこのmongoシェルはSpiderMonkeyシェルの拡張

The MongoDB distribution includes bin/mongo, the MongoDB interactive shell. This utility is a JavaScript shell that allows you to issue commands to MongoDB from the command line. (it is basically an extended SpiderMonkey shell)

The mongo Shell — MongoDB Manual

なので、Introduction to the JavaScript shell - Mozilla | MDNを見るといろいろさらにゴニョゴニョしやすいと思います。