Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Created May 30, 2012 13:40
Show Gist options
  • Save jnunemaker/2836388 to your computer and use it in GitHub Desktop.
Save jnunemaker/2836388 to your computer and use it in GitHub Desktop.
Mongo allows objects as _id. _id is always indexed and Mongo knows how to index complex objects.
require 'pp'
require 'rubygems'
require 'mongo'
conn = Mongo::Connection.new
db = conn.db('test')
col = db['test']
col.remove
oid = BSON::ObjectId.new
oid2 = BSON::ObjectId.new
(1..3).each do |num|
col.save(:_id => {:s => oid, :n => num})
end
(1..3).each do |num|
col.save(:_id => {:s => oid2, :n => num})
end
pp col.find({
:_id => {
'$gte' => {:s => oid, :n => 2},
'$lte' => {:s => oid, :n => 3},
},
}).to_a
# Example output:
# [{"_id"=>{"s"=>BSON::ObjectId('4fc623684c114f24be000001'), "n"=>2}},
# {"_id"=>{"s"=>BSON::ObjectId('4fc623684c114f24be000001'), "n"=>3}}]
require 'pp'
require 'rubygems'
require 'mongo'
conn = Mongo::Connection.new
db = conn.db('test')
col = db['test']
col.remove
oid = BSON::ObjectId.new
oid2 = BSON::ObjectId.new
(1..3).each do |num|
doc = BSON::OrderedHash.new
doc[:s] = oid
doc[:n] = num
col.save(:_id => doc)
end
(1..3).each do |num|
doc = BSON::OrderedHash.new
doc[:s] = oid2
doc[:n] = num
col.save(:_id => doc)
end
query2 = BSON::OrderedHash.new
query2[:s] = oid
query2[:n] = 2
query3 = BSON::OrderedHash.new
query3[:s] = oid
query3[:n] = 3
pp col.find({
:_id => {
'$gte' => query2,
'$lte' => query3,
},
}).to_a
# Example output:
# [{"_id"=>{"s"=>BSON::ObjectId('4fc623684c114f24be000001'), "n"=>2}},
# {"_id"=>{"s"=>BSON::ObjectId('4fc623684c114f24be000001'), "n"=>3}}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment