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

To use the DecimalField in mongoengine, you’ll need to install mongoengine library first. You can do this by running the following command:

pip install mongoengine

Now, let’s see how we can utilize the DecimalField in our code. First, import the necessary modules and create a connection to MongoDB:

from mongoengine import connect, Document, DecimalField

# Establish a connection to MongoDB
connect('my_database')

Next, define a document class that represents our MongoDB collection. We’ll include a DecimalField within this class:

class Product(Document):
    name = StringField(required=True)
    price = DecimalField(precision=2, rounding='ROUND_HALF_UP')

In the above example, we create a Product document class with two fields: name of type StringField and price of type DecimalField. We specify the precision of the decimal number with the precision argument, which denotes the number of decimal places. The rounding argument specifies the rounding mode for the decimal number.

Now we can create and save documents containing decimal values:

# Create a product
product = Product(name="Cup", price=10.99)
product.save()

To retrieve the decimal value from a document, simply access the field as you would with any other field:

# Retrieve the product and print the price
product = Product.objects(name="Cup").first()
print(product.price)  # Output: 10.99

The DecimalField in mongoengine ensures the precision and accuracy of decimal numbers, making it suitable for applications that require high-precision calculations or financial data storage.

In conclusion, the DecimalField offered by mongoengine allows you to store and manipulate decimal numbers with precision in MongoDB. It provides a convenient way to work with decimal data in Python applications while leveraging the benefits of MongoDB’s document-oriented database.