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 un开发者_运维知识库necessary load on the database?
Thanks
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):
if(!doc.containsKey("_id"))
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).
You don't have to use Bson ObjectIds as the ids in your database (see http://www.mongodb.org/display/DOCS/Object+IDs ). You are free to generate your own. The C# driver provides a way to generate ObjectIds client-side. What javascript driver are you using to call MongoDB? Does it not have a call to generate a new ObjectId?
精彩评论