Created
December 29, 2011 12:41
-
-
Save durran/1533903 to your computer and use it in GitHub Desktop.
Integer sequence ids in Mongo
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
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") |
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
Yeah we're talking another rewrite of the association code in order to make that happen, and it would definitely be slower since Mongoid would have to reiterate through all the new documents before the save of any single one to set all the ids and foreign keys instead of just setting the id when instantiated and setting the foreign key when a document is added to an association. I don't want us to start getting to AR speeds. :)