Shoken Startup Blog

KitchHike Founder/CTO

MongoDBへ様々なデータ型を保存/取得してみる。Date編

MongoDBへ様々なデータ型を保存/取得してみる。オブジェクトマッピング編 - Shoken OpenSource Society
MongoDBへ様々なデータ型を保存/取得してみる。バイナリ(BINARY)編 - Shoken OpenSource Society
MongoDBへ様々なデータ型を保存/取得してみる。Boolean編 - Shoken OpenSource Society

MongoDBへ様々なデータ型を保存/取得してみるシリーズ第4回は、Dateで日付/時間を取り扱ってみます。RubyからMongoDBへ現在時刻をinsertし、日付/時刻を条件に検索してみます。

RubyからMongoDBへ現在時刻を挿入

RubyのTimeクラスを使います。
参考
MongoDBへ様々なデータ型を保存/取得してみる。オブジェクトマッピング編 - Shoken OpenSource Society

現在時刻をMongoDBへinsertするサンプル

require 'mongo'

db_name='test'
coll_name='time_insert'

## 接続処理
db = Mongo::Connection.new.db(db_name)
coll = db.collection(coll_name)

coll.insert({:time => Time.now})

db[coll_name].find().each{ |doc|
  p doc
}

db.connection.close

実行するたびに現在時刻をinsertします。

[root@dev ruby]# ruby mongo-insert.rb
{"_id"=>BSON::ObjectId('4ff3ea4caf1fe603d1000001'), "time"=>2012-07-04 07:01:32 UTC}
{"_id"=>BSON::ObjectId('4ff3ea4daf1fe603d5000001'), "time"=>2012-07-04 07:01:33 UTC}
{"_id"=>BSON::ObjectId('4ff3ea50af1fe603d9000001'), "time"=>2012-07-04 07:01:36 UTC}
{"_id"=>BSON::ObjectId('4ff3ea51af1fe603dd000001'), "time"=>2012-07-04 07:01:37 UTC}
{"_id"=>BSON::ObjectId('4ff3ea52af1fe603e1000001'), "time"=>2012-07-04 07:01:38 UTC}
{"_id"=>BSON::ObjectId('4ff3ef2eaf1fe60bf1000001'), "time"=>2012-07-04 07:22:22 UTC}

日付/時刻を指定した検索

RubyからTimeクラスのオブジェクトを作成します。

require 'mongo'
require 'time'

db_name='test'
coll_name='time_insert'

## 接続処理
db = Mongo::Connection.new.db(db_name)
coll = db.collection(coll_name)

time_condition = Time.parse('2012-07-04')
puts "where time > #{time_condition}"

db[coll_name].find({:time => {"$gt" => time_condition}}).each{ |doc|
  p doc
}
puts

time_condition = Time.parse('2012-07-04 07:01:35 UTC')
puts "where time > #{time_condition}"

db[coll_name].find({:time => {"$gt" => time_condition}}).each{ |doc|
  p doc
}

db.connection.close

実行結果

[root@dev ruby]# ruby mongo-find-bytime.rb
where time > 2012-07-04 00:00:00 +0900
{"_id"=>BSON::ObjectId('4ff3ea4caf1fe603d1000001'), "time"=>2012-07-04 07:01:32 UTC}
{"_id"=>BSON::ObjectId('4ff3ea4daf1fe603d5000001'), "time"=>2012-07-04 07:01:33 UTC}
{"_id"=>BSON::ObjectId('4ff3ea50af1fe603d9000001'), "time"=>2012-07-04 07:01:36 UTC}
{"_id"=>BSON::ObjectId('4ff3ea51af1fe603dd000001'), "time"=>2012-07-04 07:01:37 UTC}
{"_id"=>BSON::ObjectId('4ff3ea52af1fe603e1000001'), "time"=>2012-07-04 07:01:38 UTC}
{"_id"=>BSON::ObjectId('4ff3ef2eaf1fe60bf1000001'), "time"=>2012-07-04 07:22:22 UTC}

where time > 2012-07-04 07:01:35 UTC
{"_id"=>BSON::ObjectId('4ff3ea50af1fe603d9000001'), "time"=>2012-07-04 07:01:36 UTC}
{"_id"=>BSON::ObjectId('4ff3ea51af1fe603dd000001'), "time"=>2012-07-04 07:01:37 UTC}
{"_id"=>BSON::ObjectId('4ff3ea52af1fe603e1000001'), "time"=>2012-07-04 07:01:38 UTC}
{"_id"=>BSON::ObjectId('4ff3ef2eaf1fe60bf1000001'), "time"=>2012-07-04 07:22:22 UTC}


Mongo Shellからの検索はこちらが参考になりました。
MongoDBで、日付の期間を指定して検索する方法 - DQNEO起業日記