Created
May 30, 2012 13:40
-
-
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.
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 '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}}] |
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 '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