目次

php_sample

pecl::mongo

※事前にpearインストール

# pecl install mongo
# echo "extension=mongo.so" > /etc/php.d/mongo.ini

PHP Sample

其の1

<?php
ini_set( 'display_errors', 1 );

//$mongo = new Mongo("127.0.0.1:27019");
//$mongo = new Mongo("mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019", array("replicaSet" => "replset"));
$mongo = new MongoClient("mongodb://127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019", array("replicaSet" => "replset"));

$db = $mongo->selectDB("testdb");
$col = $db->selectCollection("testcol");
$cursor = $co

Mongoは非推奨になったので、MongoClientに変更

其の2

$user = $collection->aggregate(array(
    // 指定時間以降のログ
    array(
        '$match' => array(
            "time" => array('$gte' => $start_date )
        )
    ),
    // クエリでgroup byして平均時間を集計
    array(
        '$group' => array(
            "_id" => array(
                "query"    => '$query',
                "hostname" => '$hostname',
            ),
            "time_avg"    => array( '$avg' => '$time_sum' ),
            "time_min"    => array( '$min' => '$time_min' ),
            "time_max"    => array( '$max' => '$time_max' ),
            "error_count" => array( '$sum' => '$error_count' ),
            "utime_min"   => array( '$min' => '$utime_begin' ),
            "utime_max"   => array( '$max' => '$utime_begin' ),
            "count"       => array( '$sum' => 1 ),
        )
    ),
    // クエリ、平均時間を取得
    array(
        '$project' => array(
            "_id"         => 0,
            "query"       => '$_id.query',
            "time_sum"    => '$_id.time_sum',
            "hostname"    => 1,
            "count"       => 1,
            "error_count" => 1,
            "time_avg"    => 1,
            "time_min"    => 1,
            "time_max"    => 1,
            "utime_min"   => 1,
            "utime_max"   => 1,
        )
    ),
    // 平均時間の降順(遅い順)でソート
    array(
        '$sort' => array( "time_avg" => -1 )
    ),
    // 10レコード取得
    array(
        '$limit' => 10
    )

));

リモートでエラーになる

$uri  = 'mongodb://remote:27017,remote:27018,remote:27019/';
$mongo = new Mongo($uri, array('replicaSet' => 'replset'));
Fatal error: Uncaught exception 'MongoConnectionException' with message 'No candidate servers found' in 
~
$uri  = 'mongodb://remote:27017,remote:27018,remote:27019/';
$mongo = new Mongo($uri);
Fatal error: Uncaught exception 'MongoCursorException' with message 'remote:27019: not master and slaveOk=false' in 
~
$uri  = 'mongodb://spider07:27017,spider07:27018,spider07:27019/';
$mongo = new MongoClient($uri, array('readPreference' => MongoClient::RP_SECONDARY_PREFERRED));
MongoCursor::$slaveOkay = true;
$cursor = $col->findOne();