Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Last active December 29, 2015 01:29
Show Gist options
  • Save jgaskins/7593650 to your computer and use it in GitHub Desktop.
Save jgaskins/7593650 to your computer and use it in GitHub Desktop.
Benchmarking retrieving/sorting results from MongoDB
With 115k results:
Rehearsal ----------------------------------------------------------------------
sorting Mongo query in Mongo 0.990000 0.100000 1.090000 ( 2.193201)
sorting Mongo query in Ruby 0.980000 0.030000 1.010000 ( 1.171781)
sorting Postgres query in Postgres 0.100000 0.020000 0.120000 ( 2.143469)
sorting Postgres query in Ruby 0.340000 0.030000 0.370000 ( 0.485265)
------------------------------------------------------------- total: 2.590000sec
user system total real
sorting Mongo query in Mongo 0.900000 0.040000 0.940000 ( 2.101531)
sorting Mongo query in Ruby 0.880000 0.010000 0.890000 ( 1.076933)
sorting Postgres query in Postgres 0.090000 0.010000 0.100000 ( 2.197068)
sorting Postgres query in Ruby 0.250000 0.010000 0.260000 ( 0.372697)
# The `people` collection is 1M objects with `name` and `dob` keys, generated with the following call:
# people = 1_000_000.times.map { |i| { name: i.to_s, dob: Time.now - i } }
# Both the MongoDB and Postgres examples have indexes on name and dob as well as an index containing both.
require 'benchmark'
require 'moped'
require 'pg'
mongo = Moped::Session.new(['localhost:27017'])
mongo.use 'test'
collection = mongo[:people]
mongo_query = collection.find(
'$or' => [
{ name: { '$gt'=>'900000'} },
{ dob: { '$gt' => (Time.now - 100) } }
]
)
pg = PG.connect dbname: 'test'
pg_query = %Q{SELECT * FROM people WHERE name > '900000' OR dob > '2013-10-1'::date}
results = { mongo: {}, pg: {} }
Benchmark.bmbm do |x|
x.report 'sorting Mongo query in Mongo' do
results[:mongo_mongo] = mongo_query.dup.sort(name: 1).to_a
end
x.report 'sorting Mongo query in Ruby' do
results[:mongo_ruby] = mongo_query.dup.to_a.sort_by { |person| person['name'] }
end
x.report 'sorting Postgres query in Postgres' do
results[:pg_pg] = pg.exec(pg_query + ' ORDER BY name').to_a
end
x.report 'sorting Postgres query in Ruby' do
results[:pg_ruby] = pg.exec(pg_query).to_a.sort_by { |person| person['name'] }
end
end
# Verify that both queries return the exact same results
raise 'mongo' unless results[:mongo_mongo] == results[:mongo_ruby]
raise 'postgres' unless results[:pg_pg] == results[:pg_ruby]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment