五条の比較的自由な日記

ツイッターだと短くて書けないようなことを書くためのブログ

簡単なmongodbのインストールとphpでの使用方法

なんかmongodbの使い方とインストールがややこしいと思ってる人が結構いるみたいなので、イージーモードを伝えるために書きます。

インストール

# yumリポジトリを追加
cat  << 'EOF' > /etc/yum.repos.d/mongodb.repo

[mongodb]

name=MongoDB Repository

baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/

gpgcheck=0

enabled=1

EOF


# インストール

yum install -y mongodb-org

 
# mongodをサービスに追加

systemctl enable mongod

systemctl start mongod

systemctl is-enable mongod

 

 phpのmongoドライバ
mongodってのと mongodbってのがある。phpのドキュメントによると、mongodの方は古いらしいので、mongodbを使用する。

# php56のインストール
yum install --enablerepo=remi php56-php
yum install -y php56-php-pecl-mongodb.x86_64 --enablerepo=remi

 使い方

  • insert
    テーブルとインサートしたい配列を渡すだけ。配列ならなんでもいい。$listsが数字配列でソレを展開してからインサートしている。

static function write($lists,$table)
{
    $manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');
    $bulk = new MongoDB\Driver\BulkWrite;

    foreach ($lists as $list)
    {
        $bulk->insert($list);
    }
    $manager->executeBulkWrite( $table , $bulk );
}

  • select
    テーブルとフィルターとオプションを渡すだけ。この例はフィルターの配列が空なので、全selectで、idを非表示で、dateで昇順ソート。

static function read($table)
{
    $manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017');

    $filter = array() ;
    $options = array(
        'projection' => array('_id' => 0),
        'sort' => array('date' => 1),
    );

    $query = new MongoDB\Driver\Query( $filter , $options );
    $cursor = $manager->executeQuery( $table, $query );
    foreach ($cursor as $ele)
    {
        foreach ($ele as $el)
            print $el."\t";
        print "\n";
    }
}

  • ダンプ
    test_db2test_db2という名前で、./dumpにダンプする。
mongodump --authenticationDatabase test_db2 -d test_db2 -o ./dump
  • リストア
    test_db2をdb_aaaにリストアする。

mongorestore --authenticationDatabase db_aaaa -d db_aaaa "./dump/test_db2"

  • コレクション名変更 
    コレクションaaaをbbbに変更する
db.aaa.renameCollection("bbb");

簡単。便利。高速。低セキュリティ。みんなも使おうぜ