Last active
August 29, 2015 13:56
-
-
Save takumakei/9150318 to your computer and use it in GitHub Desktop.
mongoDB + ruby + map_reduceのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source "https://rubygems.org" | |
gem "mongo" | |
gem "bson_ext" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/setup' | |
require 'mongo' | |
p Time.new | |
N = 65565 * 10 | |
conn = Mongo::Connection.new | |
test = conn.db('test') | |
foo = test.collection('foo') | |
# foo.drop(); | |
N.times { |i| | |
doc = { 'userid' => "hello world #{i}", 'cdate' => Time.new } | |
foo.insert(doc) | |
} | |
# foo.find.each { |r| p r } | |
map = %Q{ | |
function() { | |
var t = new Date(this.cdate); | |
var y = t.getFullYear(); | |
var m = t.getMonth() + 1; | |
var d = t.getDate(); | |
var k = [y, ('0' + m).slice(-2), ('0' + d).slice(-2)].join('/'); | |
emit(k, 1); | |
} | |
} | |
reduce = %Q{ | |
function(key, values) { | |
var sum = 0; | |
values.forEach(function(v) { sum = sum + v }); | |
return sum; | |
} | |
} | |
stat = test.collection('stat') | |
stat.drop(); | |
p Time.new | |
foo.map_reduce(map, reduce, { 'query' => { 'cdate' => { '$exists' => true } }, 'out' => 'stat' }); | |
p Time.new | |
stat.find.each { |r| p r } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# http://api.mongodb.org/ruby/1.9.2/ | |
# | |
require 'bundler/setup' | |
require 'mongo' | |
include Mongo | |
client = MongoClient.new('localhost', 27017) | |
p client.database_names | |
client.database_info.each { |info| puts info.inspect } | |
db = client.db("test") | |
foo = db["foo"] | |
order = [ | |
['cdate' , DESCENDING], | |
['userid', DESCENDING], | |
] | |
opts = { | |
:limit => 12, | |
:sort => order, | |
} | |
foo.find({}, opts).each { |doc| p doc } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment