Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a worldwide unique GUID/UUID system for Mongo with Python?

In the Mongo docs, it states the following:

The _id field can be of any type; however, it must be unique. Thus you can use UUIDs in the _id field instead of BSON ObjectIds (BSON ObjectIds are slightly smaller; they need not be worldwide unique, just unique for a single db cluster). When using UUIDs, your application must generate the UUID itself. Ideally the UUID is then stored in the [DOCS:BSON] type for efficiency – however you can also insert it as a hex string if you know space and speed will not be an issue for the use case.

So that being the case, can someone walk me through how I can create a bullet-proof, worldwide unique GUID in [DOCS:BSON] format for all my Mongo documents? I want to make sure that at no point will I have duplicate GUIDs, even across clusters. Does anyone have any experience with or ideas for best practices when it comes to Mongo and GUIDs? Would it be easier to use Mongos native ID system, but check for duplicates before inserting and generating a new ObjectID if need be?

like image 246
zakdances Avatar asked Aug 16 '12 15:08

zakdances


2 Answers

If you want a unique id, and don't want to use ObjectId, you probably want to use uuid4:

>>> import pymongo
>>> import uuid
>>> c = pymongo.Connection()
>>> uu = uuid.uuid4()
>>> uu
UUID('14a2aad7-fa01-40a4-8a80-04242b946ee4')
>>> c.test.uuidtest.insert({'_id': uu})
UUID('14a2aad7-fa01-40a4-8a80-04242b946ee4')
>>> c.test.uuidtest.find_one()
{u'_id': UUID('14a2aad7-fa01-40a4-8a80-04242b946ee4')}
like image 187
Bernie Hackett Avatar answered Nov 07 '22 04:11

Bernie Hackett


import uuid
uuid.uuid1()

Source: http://docs.python.org/library/uuid.html

like image 34
user1202136 Avatar answered Nov 07 '22 04:11

user1202136