Skip to main content

A MongoDB Python ORM, built on Pydantic and PyMongo.

Project description

Logo





Mongomantic = Pymongo + Pydantic

Mongomantic is a lightweight python MongoDB ORM based on Pydantic and PyMongo, heavily inspired by Mongoengine.

API

from mongomantic import BaseRepository, MongoDBModel, connect

connect("localhost:27017", "test_db")  # Setup mongodb connection

class User(MongoDBModel):
    first_name: str
    last_name: str

class UserRepository(BaseRepository):

    class Meta:  # Required internal class
        model = User  # Define model type
        collection = "user"  # Define collection name


user = User(first_name="John", last_name="Smith")

user = UserRepository.save(user)  # PyMongo wrapping classmethods
user.id  # ObjectId that was saved

Usage

pip install mongomantic

Connection to MongoDB

To connect to your database, a connect function similar to mongoengine is provided.

from mongomantic import connect

connect("localhost:27017", "test_db")  # Setup mongodb connection

Repository Usage

The BaseRepository class wraps around MongoDBModel, providing functions to save models into a collection, retrieve models, create indexes, and use the aggregation pipeline syntax on the collection.

To implement a new repository, you must first inherit from BaseRepository and provide an internal Meta class to specify the model and collection being used.

class UserRepository(BaseRepository):
    class Meta:
        model = User
        collection = "user"

And that's it! You can now access repository CRUD operations and more. More details found in the Repositories guide.

Adding indexes is simple using the Mongomantic Index model:

class UserRepository(BaseRepository):
    class Meta:
        model = User
        collection = "user"
        indexes = [
            Index(fields=["+first_name"]),
            Index(fields=["+first_name", "-last_name"], unique=True)
        ]

Safe Repository

For production use, you can either handle the errors thrown by BaseRepository in case of errors on your own, or you can use SafeRepository which handles all the errors for you and logs them, while returning meaningful safe values like None and []. Usage is exactly similar to using BaseRepository.

from mongomantic import SafeRepository, MongoDBModel, connect

connect("localhost:27017", "test_db")  # Setup mongodb connection

class User(MongoDBModel):
    first_name: str
    last_name: str

class UserRepository(SafeRepository):

    class Meta:  # Required internal class
        model = User  # Define model type
        collection = "user"  # Define collection name

user = UserRepository.get(id="123")  # DoesNotExist error handled

assert user is None

Similar to this example, all other errors are handled.

Your Opinion is Needed

Mongomantic can be kept as a simple wrapper around PyMongo, or developed into a miniature version of Mongoengine that's built on Pydantic. The first direction would result in the following API:

# Direct pymongo wrapper
users = UserRepository.find({"$and": [{"age": {"$gt": 12}}, {"name": "John"}]})

# But matches can be done as keyword arguments
john = UserRepository.find(name="John")

On the other hand, a more complex version of Mongomantic could lead to:

# More Pythonic way of writing queries
users = UserRepository.find(User.age > 12, name="John")

# Matches still compact
john = UserRepository.find(name="John")

Please submit your vote below.

Simple PyMongo Wrapper - Prefer speed and native mongodb filters More Complex Wrapper - Pythonic Filters

🚀 TODO

  • Documentation
  • Basic API similar to mongoengine, without any queryset logic
  • Built on Pydantic models, no other schema required
  • BaseRepository responsible for all operations (instead of the model itself)
  • SafeRepository derived from BaseRepository with all errors handled
  • Repository/model plugin framework (ex. SyncablePlugin, TimestampedPlugin, etc.)
  • Wrapper for aggregation pipelines
  • Mongomock tests
  • Flexible connect() function wrapper around PyMongo client (aliases, replica sets, retry writes, etc.)
  • Clean up imports and expose essentials in main file

🛡 License

License

This project is licensed under the terms of the MIT license. See LICENSE for more details.

📃 Citation

@misc{mongomantic,
  author = {mongomantic},
  title = {A MongoDB Python ORM, built on Pydantic and PyMongo.},
  year = {2021},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/RamiAwar/mongomantic}}
}

Credits

This project was generated with python-package-template.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mongomantic-0.4.2.tar.gz (13.0 kB view details)

Uploaded Source

Built Distribution

mongomantic-0.4.2-py3-none-any.whl (12.1 kB view details)

Uploaded Python 3

File details

Details for the file mongomantic-0.4.2.tar.gz.

File metadata

  • Download URL: mongomantic-0.4.2.tar.gz
  • Upload date:
  • Size: 13.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.5 CPython/3.9.2 Darwin/20.3.0

File hashes

Hashes for mongomantic-0.4.2.tar.gz
Algorithm Hash digest
SHA256 8f51a7768bdde997207e3efabb03f79c45d9497c906582463feb59251e415c23
MD5 040d2fcef4c2870d8ae616c791026427
BLAKE2b-256 1343122b9bdf92a236453aeee0236aafb1135a411ab9d40e7bcf16ff4b8d3ce1

See more details on using hashes here.

File details

Details for the file mongomantic-0.4.2-py3-none-any.whl.

File metadata

  • Download URL: mongomantic-0.4.2-py3-none-any.whl
  • Upload date:
  • Size: 12.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.5 CPython/3.9.2 Darwin/20.3.0

File hashes

Hashes for mongomantic-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 5c39f01d26ba75aef2f43e21be7e921d50525a9e8a5b9045e741c2824a0cc44f
MD5 86af9a65543f7b5611f8a2e3b2a26dbe
BLAKE2b-256 44ab7e85a29776e965fcd1873c4e509c65359ca0a972beec228aa1aea1189a90

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page