MongoDB 10.7.07 株式会社あくしゅ 三上 悟
Agenda Introduction MongoDB CRUD Index Geospatial MongoMapper
MongoDB Stable 1.4.4 Devlopment 1.5.4 hu mongo uss(huge + monstrous)  超でかい Document Database C++ Open Source GNU AGPL v3.0 Licence OSX,Linux,Windows,Solaris |32bit,64bit Development and Support:10 gen
MongoDB  vs  CouchDB MongoDB RDBMS,KeyValuc,DocumentDatabase のいいとこどりのデータベース なんでもできる。 REST ではなく、独自プロトコルを利用しているので早い CouchDB CouchDB も同じドキュメントデータベース JSON 、 Map/Reduce, スキーマレス  N-Master Replication  似ている CouchDB は用意している中で扱うには楽できるらしい。 Relax 。 詳しくは知らない。 http://www.mongodb.org/display/DOCS/Comparing+Mongo+DB+and+Couch+DB
MongoDB In Production その他いっぱい 日本のサービスは掲載されていない。
Use Cases 債券など非常に重要な取引では使わない。   RDBMS とのハイブリッド型にする 非常に高い更新が発生する問題に向いている。 例えば 頻繁な更新されるウェブサイト リアルタイム解析カウンタ ソーシャルゲーム等
Licence mongod  と  mongos  は GNU AGPL v3.0 Licence GPLv3 は組み込まれて、配布されるときに、著作権が適用される。 今日、クラウドのようにネットワーク経由で利用する場合がほとんどのため、 この抜け穴をつぶすために作られたライセンス。 GPLv3 との違いはネットワーク経由で利用した場合でも適用される。 データベースを改変したら、データベースのコードの公開が必要。 ちゃんとコミュニティーに貢献してね。 では自分のアプリケーションに組み込んだ場合はコードを公開する必要があるか? Driver は Apache License v2.0 のため、自社のウェブアプリケーションに 組み込んで利用しても、アプリケーションのソースコードの公開義務はない。 また社内で利用するアプリケーションの場合には、 データベースに改変を加えてもソースコードの公開義務はない。 http://www.mongodb.org/display/DOCS/Licensing
System Document-oriented storage Full Index Support Replication & High Availability Auto-Sharding Querying Fast In-Place Updates Map/Reduce GridFS
Collections RDB のテーブルにあたるもの BSON Documents Group
Documents RDB のレコードにあたるもの スキーマレス Key/Value(BSON) ユニークな ObjectID が付与
Field RDB のカラムにあたるもの KeyValueStore のキーにあたるもの
ObjectID BSON Object Data Type Document ID: _id Unique Index Primary Key 16 進数文字列  ObjectId( "47cc67093475061e3d95369d" )  http://www.mongodb.org/display/DOCSJP/Object+ID
ObjectID ObjectID の仕様 12バイト 4byte timestamps   (big endian) 3byte machine 2byte process id 3byte counter    (big endian) 0 1 2 3 4 5 6 7 8 9 10 11 time machine pid increment
BSON(Binaly JSON) Document に格納するデータ JSON ベース バイナリ
BSON DataType String Integer Double Date Byte array(binary data) Boolean(true and false) Null BSON object
Start/Stop MongoDB #Start mongo daemon ./bin/mongod \ --dbpath /var/lib/mongodb/ \ --port 27017 & #Stop mongo daemon kill -2 PID OR kill -15 PID
MongoDB Shell ./bin/mongo MongoDB shell >use mydb
Before Start MongoDB ではあらかじめデータベースを作る必要はありません。 何かデータを作成すると、基本的なコレクションとデータベースを 作成します。存在しないコレクションに対してクエリーを発行すると、 MongoDB は空のコレクションとして返します。  use  コマンドでデータベースを切り替えても、データベースはすぐには作成されません。データベースは、最初にデータが作成されたときに作成されます。 チュートリアルより http://www.mongodb.org/pages/viewpage.action?pageId=5079135
CRUD
CREATE SQL INSERT INTO db.mycollections(name) VALUES(“mongo”); Dynamic Querys db.mycollections.save({ name : “mongo”}); http://www.mongodb.org/display/DOCS/Inserting
READ SQL SELECT * FROM mycolletions Dynamic Querys db.mycollections.find();
READ ORDER BY & LIMIT/OFFSET SQL SELECT * FROM db.mycollections  WHERE name = “mongo” ORDER BY id DESC LIMIT 1,10;  Dynamic Querys db.mycollections.find({name:”mongo”}).sort({id: -1}).skip(1).limit(10); http://www.mongodb.org/display/DOCS/Querying
Conditional Operators $gt,$lt,$gte,$lte $ne $in $nin $mod $all $size $exists $type $elemMatch $not $where http://www.mongodb.org/display/DOCS/Advanced+Queries
Conditional Operators WHERE key = value .find({key:value}) .find({key:{Operator:value}) WHERE key Condtion value SQL Conditions MongoDB Operators key > value key:{$gt:value} key < value key:{$lt:value} key >= value key:{$gte:value} key <= value key:{$lte:value} key <> value key:{$ne:value} key IN(value) key:{$in:[value]} key NOT IN(value) key:{$nin:[value]} key EXIST(value) key:{$exist:value} SQL Conditions MongoDB Oprators key = value key:value
SELECT between SQL SELECT * FROM logs  where created_at BETWEEN ‘2010-06-10’ AND ‘2010-06-12’ Dynamic Querys db.logs.find({ created_at:{$gte:new Date(2010,6,10)}, created_at:{$lte:new Date(2010,6,12)} }); もしくは db.logs.find({ $where:&quot;this.created_at >= new Date(2010,6,10) && this.created_at <= new Date(2010,6,12)&quot; })
READ COUNT SQL SELECT COUNT(*) FROM users; Dynamic Querys db.users.count();
READ DISTINCT SQL SELECT DISTINCT(name) FROM users; Dynamic Querys db.users.distinct(“name”);
READ GROUP BY SQL SELECT name,sum(marks) FROM users  WHERE name=“mikami” GROUP BY name; Dynamic Querys db.users.group({ key:{name:true}, cond:{name:&quot;mikami&quot;}, reduce: function(obj,prev){prev.msum += obj.marks}, initial: {msum:0} }); 組み込みの Map/Reduce を使う
UPDATE db.collection.update( Criteria, ObjNew, Upsert, Multi ) Criteria アップデートするレコードを選択するためのクエリー ObjNew 対象のオブジェクトを、アップデートするオブジェクト、または  $ オペレータ ($inc など ) Upsert レコードが存在しない場合にインサートするかどうか Multi criteria  にマッチするオブジェクトすべてをアップデートするかどうか ( デフォルトでは最初に見つかったオブジェクトのみがアップデートされる ) http://www.mongodb.org/pages/viewpage.action?pageId=7209549
Modifier Operations $inc $set $unset $push $pushAll $addToSet $pop $pull $pullAll http://www.mongodb.org/display/DOCS/Updating
$inc インクリメント/デクリメント  or  シーケンシャルナンバー SQL update entries set count= count+1 where _id = '4c2bf9d691951da31517df10’ DynamicQuerys db.entries.update( {_id:ObjectId('4c2bf9d691951da31517df10')}, {$inc:{count:1}} )
$set フィールド更新 SQL update entries set name = ”ruby&quot; where user_id = 1 DynamicQuerys db.entries.update({user_id:1},{$set:{name:”ruby“}}) ※ value には配列やオブジェクトも格納できるため、まるごと値が置き換わる
$unset フィールド削除 SQL ALTER TABLE entries DROP COLUMN name; ※ すべて削除のみ DynamicQuerys db.entries.update( {_id:ObjectId('4c2bf9d691951da31517df10')}, {$unset:{name:1}} ) ※ 特定のドキュメントのフィールドだけ消すことができる
$push SQL ALTER TABLE entries ADD (body varchar(255)) UPDATE entries SET tag=&quot;MongoDB&quot; where _id = 'c2bfaea91951da31517df12'’ DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfaea91951da31517df12')} ,{$push:{tag:&quot;MongoDB&quot;}} ) tag に配列でプッシュされる。 tag = ['MongoDB'] 2回目 tag = ['MongoDB','MongoDB']
$pushAll DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfa4c91951da31517df11')}, {$push:{tag:[&quot;Ruby&quot;,&quot;Rails&quot;,&quot;MongoDB&quot;]}} ) まとめて格納できる。 tag =  [['Ruby','Rails','MongoDB']]
$addToSet DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfaea91951da31517df12')}, {$addToSet:{tag:”MongoDB&quot;}} ) tag の配列にプッシュされる。値は重複しない tag = ['MongoDB'] 2回目 tag = [‘MongoDB’]
$pop DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfaea91951da31517df12')}, {$pop:{tag:1}} ) {tag:1} の値は  1=pop -1=shift
$pull DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfaea91951da31517df12')}, {$pull:{tag:&quot;MongoDB&quot;}} ) tag で指定した値にマッチする値をすべて削除
$pullAll DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfaea91951da31517df12')}, {$pullAll:{tag:[&quot;MongoDB&quot;,&quot;Ruby&quot;]}} ) tag で指定した配列の中に含まれる値にマッチする値をすべて削除
DELETE SQL DELETE FROM db.mycollections WHERE id = 12345678900 Dynamic Querys db.mycollections.remove({_id: myobject._id});  http://www.mongodb.org/display/DOCS/Removing
DELETE SQL DELETE FROM users WHERE age < 30 Dynamic Querys db.users.remove({age:{$lt:30}});
Server Side Javascript JavascriptEngine(SpiderMonkey) v8 は開発中 ストアドプロシージャー いままで解説した関数は Javascript で定義されている ()を外すと、中の実装が見れる。 >db.test.find function (query, fields, limit, skip) { return new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip); } 中身のコード http://github.com/mongodb/mongo/tree/master/shell/
Server Side Javascript 新しく定義することもできる。 >db.system.js.save({_id: &quot;sum&quot;, value: function (x, y) { return x + y; }}); >db.eval(&quot;return sum(2, 3);&quot;); 5 直接スクリプトを実行することも可能 ./bin/mongo example.js 最近、海外で流行っている node.js との相性がいい Node.js v8 エンジンを組み込んだイベントドリブンな Web サーバー
Index
Index RDB CREATE INDEX name ON mycollections(name); MongoDB db.mycollections.ensureIndex({name: 1 }); #ASC db.mycollections.ensureIndex({name: -1 }); #DESC http://www.mongodb.org/pages/viewpage.action?pageId=5800049
Index B-Tree 指定されたキーで高速に検索が可能 _id は常にインデックスが生成される すべてのフィールドにインデックスを生成できる フィールドに配列が保存された場合、    それぞれの要素にインデックスを作成する。
Multi Key Index db.things.ensureIndex({j:1, name:-1});
Unique Index db.things.ensureIndex( {firstname: 1, lastname: 1},  {unique: true} );
Geospatial
Geospatial 地理空間を扱うための、 インデックス、クエリーがサポートされている。 Index db.map.ensureIndex({location: “2d”}) Query $near  現在地から近い位置情報を検索 $box  長方形の範囲内の位置情報を検索 $center  中心から半径の距離に含まれる位置情報を検索
Geospatial まだ開発途中 Development 1.5.4 ( 2010/07/02 Releasae) で $box,$circle の バグが解消された。 地球は丸いのに、平面で計算しているため、 正確な位置情報を取得できない。 Foursqure の中の人いわく、 近い距離 (1degree=110km) 以内なら問題ない。 Foursquare & MongoDB(http://bit.ly/cOsWa8)  ( Javascript で計算すれば可能。 パフォーマンスは未調査)
Index RDB(MySQL) INSERT INTO map(`latlng`)  VALUES(GeoFromText(POINT(35.68238, 139.7665)); CREATE SPATIAL INDEX latlng ON map(latlng); MongoDB db.map.insert(location: {lat:35.68238}, {lng:139.7665} ); db.map.ensureIndex({location: “2d”})
$near >db.places.find( { loc : { $near : [35,139] , 1 }  }).limit(10) 1 degree 以内の位置を取得する。
$center > center = [50, 50]  > radius = 10  > db.places.find( {&quot;loc&quot; :   {&quot;$within&quot; : {&quot;$center&quot; : [center, radius]}} } )
$box >box = [[40, 40], [60, 60]]  >db.places.find({&quot;loc&quot; :  {&quot;$within&quot; : {&quot;$box&quot; : box}} } )
See also Document http://www.mongodb.org/display/DOCS/Developer+Zone Cookbook http://cookbook.mongodb.org/index.html Video & Slides http://www.mongodb.org/display/DOCS/Events Articles  http://www.mongodb.org/display/DOCS/Articles
See also Slides http://www.slideshare.net/fuchaoqun/mongodb-in-action-2976022
MongoMapper http://github.com/jnunemaker/mongomapper
MongoMapper Stable 0.8.2 MongoDB を ActiveRecord を扱うように  操作できる ruby のデータベースラッパー
MongoMapper  vs  Mongoid Good Support Rails2.3 is good Plugin system ActiveRecord Building  code ( http://github.com/patcito/shapado ) Bad ・ Master/Slave replication Clusters does not support. See also: http://bit.ly/9diwYp
MongoMapper ActiveRecord class Person < ActiveRecord::Base  end MongoMapper class Person  Include MongoMapper::Document  end
gems gem install mongo_mapper #the c extensions (for production)  gem install mongo_ext
Setup config/enviroment.rb config.gem 'mongo' config.gem 'mongo_mapper' #remove ActiveRecord   config.frameworks -= [ :active_record, :active_resource ]
Schema Design class Person include MongoMapper::Document include MongoMapper::Document key :first_name, String,  :required => true  key :last_name, String , :required => true  key :age, Integer , :numeric => true  key :born_at, Time  key :active, Boolean  key :fav_colors, Array validates_presence_of :first_name  validates_presence_of :last_name  validates_numericality_of :age   End
Query Dynamic Querys db.collections.find(name:”mikami”); Mongo Mapper self.query.where(:name => “mikami”).find
See also http://blog.bitzesty.com/mongodb-with-mongomapper-and-ruby-on-rails
Contact @saicologic(Twitter Follow me!) http://d.hatena.ne.jp/saicologic/ [email_address]

Mongodb

  • 1.
  • 2.
    Agenda Introduction MongoDBCRUD Index Geospatial MongoMapper
  • 3.
    MongoDB Stable 1.4.4Devlopment 1.5.4 hu mongo uss(huge + monstrous)  超でかい Document Database C++ Open Source GNU AGPL v3.0 Licence OSX,Linux,Windows,Solaris |32bit,64bit Development and Support:10 gen
  • 4.
    MongoDB vs CouchDB MongoDB RDBMS,KeyValuc,DocumentDatabase のいいとこどりのデータベース なんでもできる。 REST ではなく、独自プロトコルを利用しているので早い CouchDB CouchDB も同じドキュメントデータベース JSON 、 Map/Reduce, スキーマレス  N-Master Replication 似ている CouchDB は用意している中で扱うには楽できるらしい。 Relax 。 詳しくは知らない。 http://www.mongodb.org/display/DOCS/Comparing+Mongo+DB+and+Couch+DB
  • 5.
    MongoDB In Productionその他いっぱい 日本のサービスは掲載されていない。
  • 6.
    Use Cases 債券など非常に重要な取引では使わない。  RDBMS とのハイブリッド型にする 非常に高い更新が発生する問題に向いている。 例えば 頻繁な更新されるウェブサイト リアルタイム解析カウンタ ソーシャルゲーム等
  • 7.
    Licence mongod と mongos は GNU AGPL v3.0 Licence GPLv3 は組み込まれて、配布されるときに、著作権が適用される。 今日、クラウドのようにネットワーク経由で利用する場合がほとんどのため、 この抜け穴をつぶすために作られたライセンス。 GPLv3 との違いはネットワーク経由で利用した場合でも適用される。 データベースを改変したら、データベースのコードの公開が必要。 ちゃんとコミュニティーに貢献してね。 では自分のアプリケーションに組み込んだ場合はコードを公開する必要があるか? Driver は Apache License v2.0 のため、自社のウェブアプリケーションに 組み込んで利用しても、アプリケーションのソースコードの公開義務はない。 また社内で利用するアプリケーションの場合には、 データベースに改変を加えてもソースコードの公開義務はない。 http://www.mongodb.org/display/DOCS/Licensing
  • 8.
    System Document-oriented storageFull Index Support Replication & High Availability Auto-Sharding Querying Fast In-Place Updates Map/Reduce GridFS
  • 9.
  • 10.
    Documents RDB のレコードにあたるものスキーマレス Key/Value(BSON) ユニークな ObjectID が付与
  • 11.
    Field RDB のカラムにあたるものKeyValueStore のキーにあたるもの
  • 12.
    ObjectID BSON ObjectData Type Document ID: _id Unique Index Primary Key 16 進数文字列  ObjectId( &quot;47cc67093475061e3d95369d&quot; ) http://www.mongodb.org/display/DOCSJP/Object+ID
  • 13.
    ObjectID ObjectID の仕様 12バイト4byte timestamps   (big endian) 3byte machine 2byte process id 3byte counter   (big endian) 0 1 2 3 4 5 6 7 8 9 10 11 time machine pid increment
  • 14.
    BSON(Binaly JSON) Documentに格納するデータ JSON ベース バイナリ
  • 15.
    BSON DataType StringInteger Double Date Byte array(binary data) Boolean(true and false) Null BSON object
  • 16.
    Start/Stop MongoDB #Startmongo daemon ./bin/mongod \ --dbpath /var/lib/mongodb/ \ --port 27017 & #Stop mongo daemon kill -2 PID OR kill -15 PID
  • 17.
    MongoDB Shell ./bin/mongoMongoDB shell >use mydb
  • 18.
    Before Start MongoDBではあらかじめデータベースを作る必要はありません。 何かデータを作成すると、基本的なコレクションとデータベースを 作成します。存在しないコレクションに対してクエリーを発行すると、 MongoDB は空のコレクションとして返します。 use コマンドでデータベースを切り替えても、データベースはすぐには作成されません。データベースは、最初にデータが作成されたときに作成されます。 チュートリアルより http://www.mongodb.org/pages/viewpage.action?pageId=5079135
  • 19.
  • 20.
    CREATE SQL INSERTINTO db.mycollections(name) VALUES(“mongo”); Dynamic Querys db.mycollections.save({ name : “mongo”}); http://www.mongodb.org/display/DOCS/Inserting
  • 21.
    READ SQL SELECT* FROM mycolletions Dynamic Querys db.mycollections.find();
  • 22.
    READ ORDER BY& LIMIT/OFFSET SQL SELECT * FROM db.mycollections WHERE name = “mongo” ORDER BY id DESC LIMIT 1,10; Dynamic Querys db.mycollections.find({name:”mongo”}).sort({id: -1}).skip(1).limit(10); http://www.mongodb.org/display/DOCS/Querying
  • 23.
    Conditional Operators $gt,$lt,$gte,$lte$ne $in $nin $mod $all $size $exists $type $elemMatch $not $where http://www.mongodb.org/display/DOCS/Advanced+Queries
  • 24.
    Conditional Operators WHEREkey = value .find({key:value}) .find({key:{Operator:value}) WHERE key Condtion value SQL Conditions MongoDB Operators key > value key:{$gt:value} key < value key:{$lt:value} key >= value key:{$gte:value} key <= value key:{$lte:value} key <> value key:{$ne:value} key IN(value) key:{$in:[value]} key NOT IN(value) key:{$nin:[value]} key EXIST(value) key:{$exist:value} SQL Conditions MongoDB Oprators key = value key:value
  • 25.
    SELECT between SQLSELECT * FROM logs where created_at BETWEEN ‘2010-06-10’ AND ‘2010-06-12’ Dynamic Querys db.logs.find({ created_at:{$gte:new Date(2010,6,10)}, created_at:{$lte:new Date(2010,6,12)} }); もしくは db.logs.find({ $where:&quot;this.created_at >= new Date(2010,6,10) && this.created_at <= new Date(2010,6,12)&quot; })
  • 26.
    READ COUNT SQLSELECT COUNT(*) FROM users; Dynamic Querys db.users.count();
  • 27.
    READ DISTINCT SQLSELECT DISTINCT(name) FROM users; Dynamic Querys db.users.distinct(“name”);
  • 28.
    READ GROUP BYSQL SELECT name,sum(marks) FROM users WHERE name=“mikami” GROUP BY name; Dynamic Querys db.users.group({ key:{name:true}, cond:{name:&quot;mikami&quot;}, reduce: function(obj,prev){prev.msum += obj.marks}, initial: {msum:0} }); 組み込みの Map/Reduce を使う
  • 29.
    UPDATE db.collection.update( Criteria,ObjNew, Upsert, Multi ) Criteria アップデートするレコードを選択するためのクエリー ObjNew 対象のオブジェクトを、アップデートするオブジェクト、または $ オペレータ ($inc など ) Upsert レコードが存在しない場合にインサートするかどうか Multi criteria にマッチするオブジェクトすべてをアップデートするかどうか ( デフォルトでは最初に見つかったオブジェクトのみがアップデートされる ) http://www.mongodb.org/pages/viewpage.action?pageId=7209549
  • 30.
    Modifier Operations $inc$set $unset $push $pushAll $addToSet $pop $pull $pullAll http://www.mongodb.org/display/DOCS/Updating
  • 31.
    $inc インクリメント/デクリメント or シーケンシャルナンバー SQL update entries set count= count+1 where _id = '4c2bf9d691951da31517df10’ DynamicQuerys db.entries.update( {_id:ObjectId('4c2bf9d691951da31517df10')}, {$inc:{count:1}} )
  • 32.
    $set フィールド更新 SQLupdate entries set name = ”ruby&quot; where user_id = 1 DynamicQuerys db.entries.update({user_id:1},{$set:{name:”ruby“}}) ※ value には配列やオブジェクトも格納できるため、まるごと値が置き換わる
  • 33.
    $unset フィールド削除 SQLALTER TABLE entries DROP COLUMN name; ※ すべて削除のみ DynamicQuerys db.entries.update( {_id:ObjectId('4c2bf9d691951da31517df10')}, {$unset:{name:1}} ) ※ 特定のドキュメントのフィールドだけ消すことができる
  • 34.
    $push SQL ALTERTABLE entries ADD (body varchar(255)) UPDATE entries SET tag=&quot;MongoDB&quot; where _id = 'c2bfaea91951da31517df12'’ DynamicQuerys db.entries.update( {_id:ObjectId('4c2bfaea91951da31517df12')} ,{$push:{tag:&quot;MongoDB&quot;}} ) tag に配列でプッシュされる。 tag = ['MongoDB'] 2回目 tag = ['MongoDB','MongoDB']
  • 35.
    $pushAll DynamicQuerys db.entries.update({_id:ObjectId('4c2bfa4c91951da31517df11')}, {$push:{tag:[&quot;Ruby&quot;,&quot;Rails&quot;,&quot;MongoDB&quot;]}} ) まとめて格納できる。 tag = [['Ruby','Rails','MongoDB']]
  • 36.
    $addToSet DynamicQuerys db.entries.update({_id:ObjectId('4c2bfaea91951da31517df12')}, {$addToSet:{tag:”MongoDB&quot;}} ) tag の配列にプッシュされる。値は重複しない tag = ['MongoDB'] 2回目 tag = [‘MongoDB’]
  • 37.
    $pop DynamicQuerys db.entries.update({_id:ObjectId('4c2bfaea91951da31517df12')}, {$pop:{tag:1}} ) {tag:1} の値は 1=pop -1=shift
  • 38.
    $pull DynamicQuerys db.entries.update({_id:ObjectId('4c2bfaea91951da31517df12')}, {$pull:{tag:&quot;MongoDB&quot;}} ) tag で指定した値にマッチする値をすべて削除
  • 39.
    $pullAll DynamicQuerys db.entries.update({_id:ObjectId('4c2bfaea91951da31517df12')}, {$pullAll:{tag:[&quot;MongoDB&quot;,&quot;Ruby&quot;]}} ) tag で指定した配列の中に含まれる値にマッチする値をすべて削除
  • 40.
    DELETE SQL DELETEFROM db.mycollections WHERE id = 12345678900 Dynamic Querys db.mycollections.remove({_id: myobject._id}); http://www.mongodb.org/display/DOCS/Removing
  • 41.
    DELETE SQL DELETEFROM users WHERE age < 30 Dynamic Querys db.users.remove({age:{$lt:30}});
  • 42.
    Server Side JavascriptJavascriptEngine(SpiderMonkey) v8 は開発中 ストアドプロシージャー いままで解説した関数は Javascript で定義されている ()を外すと、中の実装が見れる。 >db.test.find function (query, fields, limit, skip) { return new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip); } 中身のコード http://github.com/mongodb/mongo/tree/master/shell/
  • 43.
    Server Side Javascript新しく定義することもできる。 >db.system.js.save({_id: &quot;sum&quot;, value: function (x, y) { return x + y; }}); >db.eval(&quot;return sum(2, 3);&quot;); 5 直接スクリプトを実行することも可能 ./bin/mongo example.js 最近、海外で流行っている node.js との相性がいい Node.js v8 エンジンを組み込んだイベントドリブンな Web サーバー
  • 44.
  • 45.
    Index RDB CREATEINDEX name ON mycollections(name); MongoDB db.mycollections.ensureIndex({name: 1 }); #ASC db.mycollections.ensureIndex({name: -1 }); #DESC http://www.mongodb.org/pages/viewpage.action?pageId=5800049
  • 46.
    Index B-Tree 指定されたキーで高速に検索が可能_id は常にインデックスが生成される すべてのフィールドにインデックスを生成できる フィールドに配列が保存された場合、    それぞれの要素にインデックスを作成する。
  • 47.
    Multi Key Indexdb.things.ensureIndex({j:1, name:-1});
  • 48.
    Unique Index db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true} );
  • 49.
  • 50.
    Geospatial 地理空間を扱うための、 インデックス、クエリーがサポートされている。Index db.map.ensureIndex({location: “2d”}) Query $near 現在地から近い位置情報を検索 $box 長方形の範囲内の位置情報を検索 $center  中心から半径の距離に含まれる位置情報を検索
  • 51.
    Geospatial まだ開発途中 Development1.5.4 ( 2010/07/02 Releasae) で $box,$circle の バグが解消された。 地球は丸いのに、平面で計算しているため、 正確な位置情報を取得できない。 Foursqure の中の人いわく、 近い距離 (1degree=110km) 以内なら問題ない。 Foursquare & MongoDB(http://bit.ly/cOsWa8)  ( Javascript で計算すれば可能。 パフォーマンスは未調査)
  • 52.
    Index RDB(MySQL) INSERTINTO map(`latlng`) VALUES(GeoFromText(POINT(35.68238, 139.7665)); CREATE SPATIAL INDEX latlng ON map(latlng); MongoDB db.map.insert(location: {lat:35.68238}, {lng:139.7665} ); db.map.ensureIndex({location: “2d”})
  • 53.
    $near >db.places.find( {loc : { $near : [35,139] , 1 } }).limit(10) 1 degree 以内の位置を取得する。
  • 54.
    $center > center= [50, 50] > radius = 10 > db.places.find( {&quot;loc&quot; : {&quot;$within&quot; : {&quot;$center&quot; : [center, radius]}} } )
  • 55.
    $box >box =[[40, 40], [60, 60]] >db.places.find({&quot;loc&quot; : {&quot;$within&quot; : {&quot;$box&quot; : box}} } )
  • 56.
    See also Documenthttp://www.mongodb.org/display/DOCS/Developer+Zone Cookbook http://cookbook.mongodb.org/index.html Video & Slides http://www.mongodb.org/display/DOCS/Events Articles http://www.mongodb.org/display/DOCS/Articles
  • 57.
    See also Slideshttp://www.slideshare.net/fuchaoqun/mongodb-in-action-2976022
  • 58.
  • 59.
    MongoMapper Stable 0.8.2MongoDB を ActiveRecord を扱うように  操作できる ruby のデータベースラッパー
  • 60.
    MongoMapper vs Mongoid Good Support Rails2.3 is good Plugin system ActiveRecord Building code ( http://github.com/patcito/shapado ) Bad ・ Master/Slave replication Clusters does not support. See also: http://bit.ly/9diwYp
  • 61.
    MongoMapper ActiveRecord classPerson < ActiveRecord::Base end MongoMapper class Person Include MongoMapper::Document end
  • 62.
    gems gem installmongo_mapper #the c extensions (for production) gem install mongo_ext
  • 63.
    Setup config/enviroment.rb config.gem'mongo' config.gem 'mongo_mapper' #remove ActiveRecord   config.frameworks -= [ :active_record, :active_resource ]
  • 64.
    Schema Design classPerson include MongoMapper::Document include MongoMapper::Document key :first_name, String, :required => true key :last_name, String , :required => true key :age, Integer , :numeric => true key :born_at, Time key :active, Boolean key :fav_colors, Array validates_presence_of :first_name validates_presence_of :last_name validates_numericality_of :age End
  • 65.
    Query Dynamic Querysdb.collections.find(name:”mikami”); Mongo Mapper self.query.where(:name => “mikami”).find
  • 66.
  • 67.
    Contact @saicologic(Twitter Followme!) http://d.hatena.ne.jp/saicologic/ [email_address]

Editor's Notes