MongoDB
PHP Manual

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::commandデータベースコマンドを実行する

説明

public array MongoDB::command ( array $command [, array $options = array() ] )

CRUD 操作以外のほとんどすべての操作は、データベースコマンドで行います。 データベースのバージョンを知りたい? それ用のコマンドがあります。 集約が必要ですって? そのためのコマンドがあります。 ログを記録したい? もちろん可能です。

このメソッドは、次のような関数と同じ働きをします。

<?php

public function command($data) {
    return 
$this->selectCollection('$cmd')->findOne($data);
}

?>

パラメータ

command

送信したいクエリ。

options

array("オプション名" => <boolean>, ...) 形式の連想配列です。現在サポートするオプションは次のとおりです。

  • "timeout"

    整数で、デフォルトは MongoCursor::$timeout です。確認付き書き込みを使っている場合、これはクライアントがデータベースからのレスポンスを待ち続ける時間 (ミリ秒) を表します。この時間内にデータベースからの反応がなければ、MongoCursorTimeoutException をスローします。

    警告

    非推奨です。かわりに "socketTimeoutMS" オプションを使いましょう。

変更履歴

バージョン 説明
1.2.0 options パラメータと、そのオプション "timeout" が追加されました。

返り値

データベースの応答を返します。データベースの応答はすべて、 最大で 1 件のドキュメントになります。つまり、データベースへのコマンドの結果は決して 16MB を超えないということです。結果のドキュメントの構造はコマンドによって異なりますが、 大半の結果には ok フィールドがあって、これが成功したか失敗したかを表します。 また、同じく大半の結果には results フィールドもあって、 ここにドキュメントの配列が含まれます。

例1 MongoDB::command() による "distinct" の例

あるキーの、すべての異なる値を探します。

<?php

$people 
$db->people;

$people->insert(array("name" => "Joe""age" => 4));
$people->insert(array("name" => "Sally""age" => 22));
$people->insert(array("name" => "Dave""age" => 22));
$people->insert(array("name" => "Molly""age" => 87));

$ages $db->command(array("distinct" => "people""key" => "age"));

foreach (
$ages['values'] as $age) {
    echo 
"$age\n";
}

?>

上の例の出力は、 たとえば以下のようになります。


4
22
87

例2 MongoDB::command() での "distinct" の例

重複を排除したすべての値をキーから取得します。条件は、値が 18 以上であることです。

<?php

$people 
$db->people;

$people->insert(array("name" => "Joe""age" => 4));
$people->insert(array("name" => "Sally""age" => 22));
$people->insert(array("name" => "Dave""age" => 22));
$people->insert(array("name" => "Molly""age" => 87));

$ages $db->command(
    array(
        
"distinct" => "people",
        
"key" => "age"
        
"query" => array("age" => array('$gte' => 18))
    )
);  

foreach (
$ages['values'] as $age) {
    echo 
"$age\n";
}

?>

上の例の出力は、 たとえば以下のようになります。


22
87

例3 MongoDB::command() での MapReduce の例

"sale" イベント上のすべてのユーザーと、各ユーザーが何回販売したかを取得します。

<?php

// サンプルイベントドキュメント
$events->insert(array("user_id" => $id
    
"type" => $type
    
"time" => new MongoDate(), 
    
"desc" => $description));

// map 関数と reduce 関数を作ります
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    
"var sum = 0;".
    
"for (var i in vals) {".
        
"sum += vals[i];"
    
"}".
    
"return sum; }");

$sales $db->command(array(
    
"mapreduce" => "events"
    
"map" => $map,
    
"reduce" => $reduce,
    
"query" => array("type" => "sale"),
    
"out" => array("merge" => "eventCounts")));

$users $db->selectCollection($sales['result'])->find();

foreach (
$users as $user) {
    echo 
"{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

上の例の出力は、 たとえば以下のようになります。


User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).

注意: MongoCode の使用

この例で使っている MongoCode には、引数でスコープを渡すこともできます。しかし現時点では、 MongoDB は MapReduce におけるスコープの使用に対応していません。 クライアントサイドの変数を MapReduce 関数で使いたい場合は、 データベースコマンドでオプションの scope フィールドを使って グローバルスコープに追加してください。詳細な情報は » MapReduce のドキュメント を参照ください。

注意: out 引数

1.8.0 より前は out 引数がオプションでした。指定しなければ、 MapReduce の結果はテンポラリコレクションに書き出されます。これは、 接続が閉じるときに削除されます。1.8.0 以降では out 引数が必須となります。詳細な情報は » MapReduce のドキュメント を参照ください。

MapReduce を使いたい人たちのために、Prajwal Tuladhar が Mongo PHP ユーザー用の API を作成しました。これは、生のコマンドよりもよいインターフェイスを提供します。 » Github からダウンロードしましょう。 使いかたは » blog の記事 を参照ください。

例4 MongoDB::command() での "textSearch" の例

MongoDB 2.4 以降では、"text search" 機能を使った全文検索ができます。

<?php
$m 
= new MongoClient();
$d $m->demo;
$c $d->planets;

$c->insert(array("name" => "Mercury""desc" => "Mercury is the smallest and closest to the Sun"));
$c->insert(array("name" => "Venus""desc" => "Venus is the second planet from the Sun, orbiting it every 224.7 Earth days."));
$c->insert(array("name" => "Earth""desc" => "Earth is the the densest of the eight planets in the Solar System."));
$c->insert(array("name" => "Mars""desc" => "Mars is named after the Roman god of war."));

$c->ensureIndex(array('desc' => 'text'));

$r $d->command(array("text" => "planets"'search' => "sun" ));
print_r($r);
?>

上の例の出力は、 たとえば以下のようになります。


Array
(
[queryDebugString] => sun||||||
[language] => english
[results] => Array
(
[0] => Array
(
[score] => 0.625
[obj] => Array
(
[_id] => MongoId Object
(
[$id] => 517549d944670a4a5cb3059a
)

[name] => Mercury
[desc] => Mercury is the smallest and closest to the Sun
)

)

[1] => Array
(
[score] => 0.55
[obj] => Array
(
[_id] => MongoId Object
(
[$id] => 517549d944670a4a5cb3059b
)

[name] => Venus
[desc] => Venus is the second planet from the Sun, orbiting it every 224.7 Earth days.
)

)

)

[stats] => Array
(
[nscanned] => 2
[nscannedObjects] => 0
[n] => 2
[nfound] => 2
[timeMicros] => 95
)

[ok] => 1
)

例5 MongoDB::command() での "geoNear" の例

この例は、geoNear コマンドの使い方を示すものです。

<?php
$m 
= new MongoClient();
$d $m->demo;
$c $d->poiConcat;

$r $d->command(array(
    
'geoNear' => "poiConcat",      // poiConcat コレクション内を検索します
    
'near' => array(-0.0851.48), // 北緯 51.48°、東経 0.08° 近辺を検索します
    
'spherical' => true,           // 球状検索を有効にします
    
'num' => 5,                    // 最大 5 件までの結果を返します
));
print_r($r);
?>

参考

MongoDB コアドキュメントの » database commands そして各コマンドのドキュメント » findAndModify» getLastError および » repairDatabase (他にもたくさんあります。これは単なる例です) を参照ください。


MongoDB
PHP Manual