MongoDBインストール
MongoDBを使ってみました。
今回は時間がないのでインストールのみです。
環境
OS:CentOS6.4
インストール
環境に合わせたインストール手順はこちらです。
mongoサーバの起動
コマンド1つで起動できます
sudo service mongod start
サーバの容量が 3.4GB以上ない場合は、エラーが出てしまいます。
$ sudo service mongod startStarting mongod: about to fork child process, waiting until server is ready for connections.forked process: 1698all output going to: /var/log/mongo/mongod.logERROR: child process failed, exited with error number 100[失敗]
エラーログを見ると、journal filesが3379MB必要らしいです。
sudo less /var/log/mongo/mongod.logTue Dec 17 00:10:12.189 [initandlisten] journal dir=/var/lib/mongo/journalTue Dec 17 00:10:12.194 [initandlisten] recover : no journal files present, no recovery neededTue Dec 17 00:10:12.196 [initandlisten]Tue Dec 17 00:10:12.196 [initandlisten] ERROR: Insufficient free space for journal filesTue Dec 17 00:10:12.199 [initandlisten] Please make at least 3379MB available in /var/lib/mongo/journal or use --smallfilesTue Dec 17 00:10:12.199 [initandlisten]
容量もないのでnojournal=trueに設定を変更します。
18 # Disables write-ahead journaling19 # nojournal = true↓18 # Disables write-ahead journaling19 nojournal = true
設定変更後は無事起動できました。
$ sudo service mongod start
Starting mongod: about to fork child process, waiting until server is ready for connections.
forked process: 5086
all output going to: /var/log/mongo/mongod.log
child process started successfully, parent exiting
[ OK ]
クライアントから実行
利用できるクライアントはphpやruby、scalaなどたくさんあります
Install MongoDB — MongoDB Manual 2.4.8
今回もphpを使ってmongoDBを利用します。手順はThe MongoDB Blogと同じです。
phpizeを使えるようにする
sudo pecl install mongo
php.iniに設定を追加
$ cat /etc/php.d/myext.iniextension=mongo.so
保存
phpからmongoDBに保存。
$ cat save.php<?php// DATA$user = array('first_name' => 'MongoDB','last_name' => 'Fan','tags' => array('developer','user'));// Configuration$dbhost = 'localhost';$dbname = 'test';// Connect to test database$m = new Mongo("mongodb://$dbhost");$db = $m->$dbname;// Get the users collection$c_users = $db->users;// Insert this new document into the users collection$c_users->save($user);
実行
データの確認
mongoのtestDBにログインして確認。oracleのsqlplusのようなものです。
$ mongo testMongoDB shell version: 2.4.8connecting to: test> show collections;system.indexesusers> db.users.findOne(){"_id" : ObjectId("52af1de83b5823ab138b4567"),"first_name" : "MongoDB","last_name" : "Fan","tags" : ["developer","user"]}
読み込み
読み込みコード
$ cat load.php<?php// Configuration$dbhost = 'localhost';$dbname = 'test';// Connect to test database$m = new Mongo("mongodb://$dbhost");$db = $m->$dbname;// Get the users collection$c_users = $db->users;// Find the user with first_name 'MongoDB' and last_name 'Fan'$user = array('first_name' => 'MongoDB','last_name' => 'Fan');$user = $c_users->findOne($user);var_dump($user);
実行
無事に保存と取得ができました!