Skip to content

Instantly share code, notes, and snippets.

@durran
Created December 29, 2011 12:41
Show Gist options
  • Save durran/1533903 to your computer and use it in GitHub Desktop.
Save durran/1533903 to your computer and use it in GitHub Desktop.
Integer sequence ids in Mongo
Mongoid.database.add_stored_function "sequence", <<-__
function(name) {
var ret = db.counters.findAndModify({ query: { _id: name}, update: { $inc : { next: 1}}, "new" :true, upsert: true});
return ret.next;
}
__
class Sequence
include Mongoid::Fields::Serializable
def deserialize(object)
object.to_i
end
def serialize(object)
Mongoid.master.eval("sequence('#{object}')").to_i
end
end
class A
include Mongoid::Document
field :_id, :type => Sequence
end
A.create(:_id => "as")
@ahoward
Copy link

ahoward commented Jan 7, 2012

yes i can understand that. somewhat humorously i have actually had AR projects configured so that it assignes ids up front to make circular associations simpler ;-)

you know, top level ids and intra-document ids are not really the same thing.... i've considered before both having nice ids on top level docs and object_ids for intra-document relations...

in the end it is indeed very difficult to beat the overall tradoffs object_ids provide. lately i've just been slugging the top level namespace in my urls, for instance

/dojo4/posts/comments/$object_id

and that addresses the 80% rule pretty well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment