Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Help with MongoDB and unique id generation

Help with MongoDB and unique id generation


Right now we're doing all of our unique id Generation by using MongoDB's baked in ids. We have some instances where we need to create an id for a object before we add anything to the database.

We could create an entry get the id and then delete the entry if we end up never needing it, but I would rather not put that load on the system for such an easy task. Is there any way to be in sync with mongos native methods for doing this without putting unnecessary load on the database?


Problem courtesy of: fancy


This is pretty simply to do. With the exception of upsert operations the ObjectId is client side generated. In other words, when you perform a save operation from within your app the Driver will automatically do (pseudo):

    doc.put(_id, new ObjectId());

So all you have to do is generate an ObjectId yourself, do whatever you need to do with it and then set the _id of your Document to that value rather than have the mongo driver do it for you.

Note that this is exactly as safe as having the driver generated the IDs. ObjectIds are designed to eliminate ID collisions (read: make it unlikely to the point of collisions becoming irrelevant). Also, the time between generating the id and storing it also does not introduce ID collision issues.

If you save a document with an _id that already exists in the database it will overwrite the original document with that _id.

If you insert a document with an _id that already exists you will get a duplicate _id error (error 11000).

Solution courtesy of: Remon van Vliet


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Help with MongoDB and unique id generation


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription