TyMongo is a Python package designed to simplify your interaction with MongoDB by leveraging the power of pymongo for database connectivity and pydantic for efficient modeling and type creation through classes.
- Seamless connection to MongoDB using pymongo. π
- Data modeling and type creation with pydantic classes. π§±
- Automatic data validation and type conversion. β
- Automatic data serialization and deserialization. π¦
To install TyMongo, simply use pip:
pip install tymongoAll you really need to do is to create .env file in your project root directory and add the following variables:
DATABASE_URL=your_database_url
DATABASE_NAME=your_database_nameAnd now you're ready to go! π
To create a model, simply inherit from TyMongoModel and define your fields:
class User(TyMongoModel):
name: str
age: int
class Config:
collection = "users"- Will work 100% like
BaseModelfrom pydantic, but with some extra features. π€© - Make sure you define inner class
Configand setcollectionto the name of the collection you want to use in your database. π - You don't have to define
_idfield, it will be automatically created for you. π
user = User(name="Majid", age=21)
# or
user_dict = {"name": "Majid", "age": 21}
user = User(**user_dict)- You can pass any value to any field, it will be automatically converted to the type you defined. π
- You can also pass a dictionary to the model, it will be automatically converted to the model. π
user.save()Now you have a new user in your database! π
user.age = 22
user.save()Now your user's age is 22 in your database! π
user.delete()Now your user is deleted from your database! π
query = {"age": 22}
users = User.find(query)Just like pymongo, you can pass a query to find method and it will return a list of all the users that match the query as a list of models, just make sure the dictionary keys match the model fields. π
query = {
'x': 'some value',
'age': 21,
}
users = User.find(query)This will raise an error because x is not a field in the model. β
user = User.get("xxxxxxxxxxxxxxxxxxxxxxxx")q = {
'name' : 'Majid'
}
user = User.find_one(q)You can access the collection object directly from the model:
collection = User.__collection__()
users = collection.find({"age": 22})TyMongo is licensed under the terms of the MIT License.
Thank you for using TyMongo! π happy coding! π
