[파이썬] mongoengine `UUIDField` 활용하기

Mongoengine is a powerful object-document mapper (ODM) for MongoDB in Python. It provides a straightforward way to work with MongoDB documents using Python classes and objects. One useful feature of Mongoengine is the UUIDField, which allows you to store universally unique identifiers (UUIDs) in your MongoDB documents.

What is a UUID?

A UUID is a 128-bit unique identifier that is typically represented as a string of hexadecimal digits separated by hyphens. UUIDs are commonly used in distributed systems to uniquely identify resources or entities. Unlike traditional numeric IDs, UUIDs are designed to be globally unique, meaning the chances of generating the same UUID in different systems are extremely low.

Using UUIDField in Mongoengine

To use the UUIDField in Mongoengine, you first need to import it from the mongoengine.fields module. Here’s an example of how you can define a UUIDField in a Mongoengine document class:

from mongoengine import Document, UUIDField

class MyDocument(Document):
    uuid = UUIDField(required=True)

In the above code, we define a MyDocument class that inherits from Document (a base class provided by Mongoengine). We then declare a uuid field of type UUIDField in the MyDocument class.

Generating UUIDs

To generate UUIDs in Python, you can use the uuid module, which is part of the Python standard library. The uuid module provides a uuid4() function that generates random UUIDs. Here’s an example of how you can generate a UUID and save it to a MyDocument instance:

from uuid import uuid4

my_uuid = uuid4()
my_doc = MyDocument(uuid=my_uuid)
my_doc.save()

In the above code, we first import the uuid4() function from the uuid module. We then generate a random UUID using uuid4() and assign it to the uuid field of a MyDocument instance. Finally, we save the document to the MongoDB database using the save() method.

Querying UUIDs

To query documents based on their UUIDs, you can use the UUIDField as a filter in your Mongoengine queries. Here’s an example:

# Find a document with a specific UUID
my_doc = MyDocument.objects(uuid=my_uuid).first()

# Find all documents with UUIDs greater than a certain value
docs = MyDocument.objects(uuid__gt=my_uuid)

# Find all documents with UUIDs within a certain range
docs = MyDocument.objects(uuid__range=(low_uuid, high_uuid))

In the above code, we use the objects() method to query documents from the MyDocument collection. We filter the documents using the uuid field and perform operations such as equality (uuid=my_uuid), greater than (uuid__gt=my_uuid), and range (uuid__range=(low_uuid, high_uuid)).

Conclusion

The UUIDField in Mongoengine provides a convenient way to store and query UUIDs in your MongoDB documents. By leveraging the power of UUIDs, you can ensure uniqueness across distributed systems and simplify record identification.