[파이썬] mongoengine 도큐먼트 저장 및 불러오기

MongoEngine is a Python Object-Document Mapper (ODM) that simplifies the interaction with MongoDB databases. In this blog post, we will explore how to save and retrieve documents using MongoEngine in Python.

Installation

Before we get started, make sure you have MongoEngine installed on your machine. You can install it using pip:

pip install mongoengine

Saving Documents

To save a document using MongoEngine, we need to define a Model class that inherits from the mongoengine.Document class. Let’s create a simple example of a User document:

from mongoengine import Document, StringField, IntField

class User(Document):
    name = StringField(required=True)
    age = IntField(required=True)
    email = StringField()

    meta = {
        'collection': 'users'
    }

In the above code, we created a User class with three fields: name, age, and email. The name and age fields are required, while the email field is optional. The meta dictionary is used to specify the collection name where the documents will be stored in the MongoDB database.

To save a new user to the database, we can create an instance of the User class and call the save() method:

user = User(name='John Doe', age=25, email='john.doe@example.com')
user.save()

Retrieving Documents

MongoEngine provides several ways to retrieve documents from the database. We can use the get() method to retrieve a single document based on a specific condition:

user = User.objects.get(name='John Doe')

In the above code, we use the objects attribute of the User class to access the collection and call the get() method with the desired condition.

We can also use the filter() method to retrieve multiple documents that match a certain condition:

users = User.objects.filter(age__gte=30)

In the above code, we retrieve all users with an age greater than or equal to 30.

To retrieve all documents in a collection, we can use the all() method:

users = User.objects.all()

Conclusion

MongoEngine provides a convenient way to save and retrieve documents in a MongoDB database using Python. In this blog post, we learned how to define a Model class, save documents, and retrieve them based on specific conditions. This is just a basic introduction to MongoEngine, and there are many more features and functionalities available. I encourage you to explore the official documentation to learn more about this powerful ODM.

Happy coding!